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

4

23

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?

Baksheesh answered 19/1, 2011 at 23:11 Comment(2)
Is it a requirement to use Runtime?Chick
@Navi: Is there an alternative?! Tell. I want to know! Or do you mean to use a ProcessBuilderHeshum
L
40

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) {
       // ...
     }
}
Lao answered 19/1, 2011 at 23:26 Comment(0)
B
5

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.

Bathsheba answered 19/1, 2011 at 23:28 Comment(0)
L
2

System.out is NOT the stdout from the new process you spawned by calling exec(). If you want to see the "HelloWorld2" you must get the Process returned from the exec() call, then call getOutputStream() from that.

Liberalism answered 19/1, 2011 at 23:26 Comment(0)
F
0

Simpler way to achieve objective:

    ProcessBuilder builder = new ProcessBuilder("hostname");
    Process process = builder.start();
    Scanner in = new Scanner(process.getInputStream());
    System.out.println(in.nextLine()); // or use iterator for multilined output
Fannie answered 18/6, 2019 at 12:55 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.