捕获Java中正在运行的进程的输出

时间:2015-03-10 18:38:02

标签: java process stdout

(我使用的是Windows 7)我知道如何启动进程,传递一些参数并读取该进程的输出。

import java.io.*;
class Test {
    public static void main(String args[]) throws IOException  {
        ProcessBuilder pb
                = new ProcessBuilder("java", "ProgramFoo", "ArgBar");
        Process process = pb.start();
        final InputStream is = process.getInputStream();
            BufferedReader reader
                    = new BufferedReader(new InputStreamReader(is));
            String line;
            while ((line = reader.readLine()) != null) {
                System.out.println(line);
            }
    }
}

但我想要做的是阅读正在运行的进程的输出。也许是通过它的PID或名称。

任何想法?

1 个答案:

答案 0 :(得分:-1)

查看http://commons.apache.org/proper/commons-exec/以更好地处理流程。

或者,您可以从已有的进程中获取InputStream,并按以下方式读取它:

BufferedReader br = new BufferedReader(new InputStreamReader(process.getInputStream()));

StringBuffer stringBuffer = new StringBuffer();

stdout = br.readLine();
while (stdout != null) {
    stringBuffer.append(stdout);
    stdout = br.readLine();
}