java - 用java获取一个进程的输出结果

标签 java processbuilder

我想执行一个进程一段时间,然后获取输出并销毁该进程。这是我的代码

BufferedReader stdInput = new BufferedReader(new InputStreamReader(p.getInputStream()));
BufferedReader temp;
p.waitFor(7, TimeUnit.SECONDS);
temp=stdInput;
p.destroy(); 
System.out.println(temp.readLine());

但我得到了结果

java.io.IOException: Stream closed

如何在执行过程 7 秒后复制结果?如果我使用这段代码

p.waitFor(7, TimeUnit.SECONDS);
while ((inputRead=stdInput.readLine()) != null){
    Helper.log(inputRead);
}

while 循环永远不会终止,因为在 waitFor 之后进程仍然存在,所以我必须销毁它。如果我破坏了进程,我将无法再获取 stdInput 的内容。

最佳答案

您不希望调用 waitFor(),因为它会一直等到进程被销毁。只要 InputStream 打开,您也不希望读取,因为这样的读取只有在进程被终止时才会终止。

相反,您可以简单地启动该过程,然后等待 7 秒。一旦 7 秒过去,读取缓冲区中的可用数据而不等待流关闭:

BufferedReader stdInput = new BufferedReader(new InputStreamReader(p.getInputStream()));
Thread.sleep(7000); //Sleep for 7 seconds
while (stdInput.ready()) { //While there's something in the buffer
     //read & print - replace with a buffered read (into an array) if the output doesn't contain CR/LF
    System.out.println(stdInput.readLine()); 
}
p.destroy(); //The buffer is now empty, kill the process.

如果进程继续打印,那么 stdInput.ready() 总是返回 true 你可以尝试这样的事情:

BufferedReader stdInput = new BufferedReader(new InputStreamReader(p.getInputStream()));
char[] buffer = new char[16 * 1024]; // 16 KiB buffer, change size if needed
long startedReadingAt = System.currentTimeMillis(); //When did we start reading?
while (System.currentTimeMillis() - startedReadingAt < 7000) { //While we're waiting
    if (stdInput.ready()){
        int charsRead = stdInput.read(buffer); //read into the buffer - don't use readLine() so we don't wait for a CR/LF
        System.out.println(new String(buffer, 0, charsRead));  //print the content we've read
    } else {
        Thread.sleep(100); // Wait for a while before we try again
    }
}
p.destroy(); //Kill the process

在此解决方案中,线程没有 hibernate ,而是在接下来的 7 秒内从 InputStream 读取数据,然后关闭进程。

关于java - 用java获取一个进程的输出结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40194017/

相关文章:

java - 有没有更好的方法来读取进程的输入流,然后使用指定的方法进行处理?

java.io.IOException : Cannot run program "": CreateProcess error=2, 系统找不到指定的文件

java - 如何禁用 MapStruct 中源映射中的字段?

java - 如何在 Java 中将 TCP 发送按钮放入循环中?

java - 在shell脚本中设置环境变量并在Java程序中访问

java - 当我从 cmd 重定向输出时,为什么输出文件为空?

java - 使用流程构建器

java - 选择位置图像不会显示在 ImageView 上

java - 从 ArrayList 适配器设置可见 View ,该 View 驻留在与 Activity 不同的文件中

java - 如何反转 DSpace 中项目 View 的显示顺序?