3

我正在使用 Java 创建一个 GUI。此 GUI 使用 ProcessBuilder 类从命令行启动程序。

关于正在启动的进程的一些信息:从命令行,它创建另一个窗口并将信息打印到所述窗口。

在我的 GUI 窗口中,我有一个文本区域,我想将所述输出重定向到该区域。我最初打算使用 SwingWorker 对象来不断检查更多输出,而不是阻止 GUI。为了测试并确保我保留了原始语法(甚至没有将 GUI 带入其中),我想我会将辅助进程窗口的输出打印到 System.out。但是,似乎有些问题,因为我可以在辅助进程的窗口中看到输出,但看不到我正在使用的终端。

代码摘录如下:

Process p = pb.start(); 
Scanner s = new Scanner(p.getInputStream());

SwingWorker pipe = new SwingWorker<String, Void> (){
    public String doInBackground(){
        while(run){
            if(s.hasNextLine()){
                System.out.println("S has next!");
                System.out.println(s.nextLine());
            }
        }
        return null;
    }
};
pipe.execute();

布尔运行在程序的其他地方定义,并在进程 p 退出或强制退出时设置为 false (附加问题:这是一个非常糟糕的主意吗?我觉得它可能是......)。

有没有人知道为什么当我看到它被打印到另一个窗口时我从来没有得到任何输出?最初我的反应是使用 p.getOutputStream() 但 Scanner 没有将 outputStream 作为参数。

感谢您的时间。

4

2 回答 2

3

You should also scan p.getErrorStream() - some programs write to STDERR which is indistinguishable from STDOUT when run from the command line. It is generally good practice to consume both streams, as if either one is not consumed it can cause the external process to hang.

于 2010-01-05T22:55:35.150 回答
2

如果外部进程正在将其输出写入自己的窗口,则几乎可以肯定输出没有写入 STDOUT,这就是您正在使用代码读取的内容。如果这样做,则外部程序的输出将同时出现在其窗口和启动它的命令行会话中(如果存在的话)。如果无法访问外部程序的源代码,除非作者为该功能(即,将输出重定向到 STDOUT 而不是窗口的命令行开关)做出规定,否则您不太可能截获其输出。

As to p.getOutputStream(), that returns a stream which is "output" from YOUR point of view -- i.e. you write to it to send data to the process' STDIN. Your use of p.getInputStream() would be correct for the case where the external program writes to its STDOUT.

于 2010-01-05T18:55:29.090 回答