0

假设您正在 Eclipse 中运行一个简单的 HelloWorld 程序。的输出System.out.println("Hello, World!");在“控制台”选项卡中清晰可见。但是,如果您随后打开“调试”透视图并显示“进程属性”窗口,您将看到如下内容:

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

所以,看起来它正在使用 javaw.exe 来启动 JVM。但是,如果您从命令行运行完全相同的命令,您将看不到任何输出(正如您所期望的,因为 javaw 应该与 stdout 和 stderr 分离)。

那么,Eclipse 如何捕获和显示该输出?我也希望能够做到这一点...

4

2 回答 2

0

要在 Java 中为外部进程重定向输出流,可以使用ProcessBuilder类。

示例用法

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);
    }
}

示例输出

java版本“1.8.0_144”
Java(TM) SE 运行时环境 (build 1.8.0_144-b01)
Java HotSpot(TM) 64 位服务器 VM(内部版本 25.144-b01,混合模式)
0
于 2017-10-13T18:04:23.903 回答
0

创建您自己的 PrintStream 并使用 System.setOut(PrintStream out) 方法。

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");
    }
}
于 2017-10-13T17:44:01.447 回答