Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

I have a program Test.java:

import java.io.*;  public class Test {     public static void main(String[] args) throws Exception {         System.setOut(new PrintStream(new FileOutputStream("test.txt")));         System.out.println("HelloWorld1");         Runtime.getRuntime().exec("echo HelloWorld2");     } } 

This is supposed to print HelloWorld1 and HelloWorld2 to the file text.txt. However, when I view the file, I only see HelloWorld1.

  1. Where did HelloWorld2 go? Did it vanish into thin air?

  2. Lets say I want to redirect HelloWorld2 to test.txt also. I can't just add a ">>test.txt" in the command because I'll get a file already open error. So how do I do this?

like image 882
Leo Izen Avatar asked Jan 19 '11 23:01

Leo Izen


1 Answers

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) {        // ...      } } 
like image 149
martin clayton Avatar answered Jan 06 '23 00:01

martin clayton