How does Eclipse capture stdout from a process started with javaw.exe?

496 Views Asked by At

Let's say you're running a simple HelloWorld program in Eclipse. The output of System.out.println("Hello, World!"); is clearly visible in the 'Console' tab. However, if you then open the 'Debug' perspective and display the 'Process properties' window, you'll see something like this:

Path:
C:\Program Files\Java\jdk1.8.0_144\bin\javaw.exe

Working Directory:
C:\eclipse-workspace\HelloWorld

Command Line:
"C:\Program Files\Java\jdk1.8.0_144\bin\javaw.exe" 
-Dfile.encoding=Cp1250 
-classpath "<blah-blah>" 
HelloWorld

So, it looks like it's using javaw.exe to launch the JVM. But if you run the exact same command from the command line, you won't see any output (just as you would expect, because javaw is supposed to be detached from stdout and stderr).

So, how does Eclipse capture and display that output? I'd like to be able to do the same...

2

There are 2 best solutions below

0
DragonAssassin On BEST ANSWER

To redirect output streams for an external process in Java, you can use the ProcessBuilder class.

Example Usage

public class Main {
    public static void main(String[] args) throws Exception {
        ProcessBuilder pb = new ProcessBuilder("javaw", "-version")
                .inheritIO();
        Process p = pb.start();
        int returnValue = p.waitFor();
        System.out.println(returnValue);
    }
}

Example Output

java version "1.8.0_144"
Java(TM) SE Runtime Environment (build 1.8.0_144-b01)
Java HotSpot(TM) 64-Bit Server VM (build 25.144-b01, mixed mode)
0
0
Andriy Slobodyanyk On

Create your own PrintStream and use System.setOut(PrintStream out) method.

public class RedirectSystemOut {
     public static void main(String[] args) throws FileNotFoundException {
         System.out.println("This goes to the console");
         PrintStream console = System.out;

         File file = new File("out.txt");
         FileOutputStream fos = new FileOutputStream(file);
         PrintStream ps = new PrintStream(fos);
         System.setOut(ps);
         System.out.println("This goes to out.txt");

         System.setOut(console);
         System.out.println("This also goes to the console");
    }
}