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?

2
  • Is it a requirement to use Runtime? Commented Jan 19, 2011 at 23:24
  • @Navi: Is there an alternative?! Tell. I want to know! Or do you mean to use a ProcessBuilder Commented Jan 20, 2011 at 7:39

4 Answers 4

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) {
       // ...
     }
}
Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

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.

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.