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...
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