Please clarify the problem in the java code below.

import java.lang.Process; import java.io.*; import java.io.InputStream; import java.io.IOException; public class prgms{ public static void main(String[] args) { try { // Execute a command without arguments String command = "java JavaSimpleDateFormatExample"; Process child = Runtime.getRuntime().exec(command); // Execute a command with an argument // command = "java JavaStringBufferAppendExample"; //child = Runtime.getRuntime().exec(command); } catch (IOException e) { } InputStream in = child.getInputStream(); int c; while ((c = in.read()) != -1) { process((char)c); } in.close(); } } 

I changed this way ... but the following error occurs,

 prgms.java:17: cannot find symbol symbol : variable child location: class prgms InputStream in = child.getInputStream(); ^ prgms.java:20: cannot find symbol symbol : method process(char) location: class prgms process((char)c); ^ 2 errors 
0
source share
3 answers

You really ignore the stdout and stderr Process threads returned by Runtime#exec() .

It will be a long story, so here is just a link: When Runtime.exec will not . Read all four pages.

+8
source

No problem with this code.

What happens is the execution of another Java program inside.

There is a method in the Process class to get the output of the program, you need to redirect this output to your own if you want to see the result.

Here's a sample using the "modern" alternative to Runtime.exec

 // Hello.java says Hello to the argument received. class Hello { public static void main ( String [] args ) { System.out.println( "Hello, "+args[ 0 ] ); } } // CallHello.java // Invokes Hello from within this java program // passing "world" as argument. import java.io.InputStream; import java.io.IOException; public class CallHello { public static void main( String [] args ) throws IOException { Process child = new ProcessBuilder("java", "Hello", "world").start(); // read byte by byte the output of that progam. InputStream in = child.getInputStream(); int c = 0; while( ( c = in.read() ) != -1 ) { // and print it System.out.print( (char)c); } } } 

Output:

 Hello world 
+4
source

A child is declared inside a try ... catch block, so its scope is local to that block. You are trying to access it outside of the block. You should declare it before the block, something like

 Process child; try { // code child = Runtime.getRuntime().exec(command); // code } catch(/*blah blah*/) {} // more code 
+2
source