我想执行一个进程一段时间,然后获取输出并销毁该进程。这是我的代码
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/