Redirect Runtime.getRuntime().exec() output with System.setOut();

Since JDK 1.5 there is java.lang.ProcessBuilder which handles std and err streams as well. It's sort of the replacement for java.lang.Runtime and you should be using it.


The standard output of Runtime.exec is not automatically sent to the standard output of the caller.

Something like this aught to do - get access to the standard output of the forked process, read it and then write it out. Note that the output from the forked process is availble to the parent using the getInputStream() method of the Process instance.

public static void main(String[] args) throws Exception {
    System.setOut(new PrintStream(new FileOutputStream("test.txt")));
    System.out.println("HelloWorld1");

     try {
       String line;
       Process p = Runtime.getRuntime().exec( "echo HelloWorld2" );

       BufferedReader in = new BufferedReader(
               new InputStreamReader(p.getInputStream()) );
       while ((line = in.readLine()) != null) {
         System.out.println(line);
       }
       in.close();
     }
     catch (Exception e) {
       // ...
     }
}