如何在Java中处理多个流? [英] How do I handle multiple streams in Java?
问题描述
我正在尝试运行一个进程,并对其输入,输出和错误流进行处理。显而易见的方法是使用类似 select()
的东西,但我在Java中唯一可以找到的就是 Selector.select ()
,它需要频道
。似乎无法从 InputStream
或 OutputStream <获取
频道
/ code>( FileStream
有一个 getChannel()
方法,但这对此没有帮助)
I'm trying to run a process and do stuff with its input, output and error streams. The obvious way to do this is to use something like select()
, but the only thing I can find in Java that does that is Selector.select()
, which takes a Channel
. It doesn't appear to be possible to get a Channel
from an InputStream
or OutputStream
(FileStream
has a getChannel()
method but that doesn't help here)
所以,我编写了一些代码来轮询所有流:
So, instead I wrote some code to poll all the streams:
while( !out_eof || !err_eof )
{
while( out_str.available() )
{
if( (bytes = out_str.read(buf)) != -1 )
{
// Do something with output stream
}
else
out_eof = true;
}
while( err_str.available() )
{
if( (bytes = err_str.read(buf)) != -1 )
{
// Do something with error stream
}
else
err_eof = true;
}
sleep(100);
}
有效,但它永远不会终止。当其中一个流到达文件末尾时, available()
返回零,因此 read()
未被调用我们永远不会得到表示EOF的-1返回。
which works, except that it never terminates. When one of the streams reaches end of file, available()
returns zero so read()
isn't called and we never get the -1 return that would indicate EOF.
一种解决方案是检测EOF的非阻塞方式。我无法在任何地方看到文档中的一个。或者有更好的方法来做我想做的事情吗?
One solution would be a non-blocking way to detect EOF. I can't see one in the docs anywhere. Alternatively is there a better way of doing what I want to do?
我在这里看到这个问题:
链接文本
虽然它并不完全按照我的意愿行事,但我可能会使用这个想法,为每个流产生单独的线程,以解决我现在遇到的特殊问题。但当然这不是唯一的方法吗?当然必须有一种方法可以从多个流中读取而不使用每个线程?
I see this question here: link text and although it doesn't exactly do what I want, I can probably use that idea, of spawning separate threads for each stream, for the particular problem I have now. But surely that isn't the only way to do it? Surely there must be a way to read from multiple streams without using a thread for each?
推荐答案
如你所说,解决方案<本答案中概述的href =https://stackoverflow.com/questions/60302/starting-a-process-with-inherited-stdinstdoutstderr-in-java-6#60578是传统的方式从进程中读取stdout和stderr。每个流的线程是可行的,即使它有点烦人。
As you said, the solution outlined in this Answer is the traditional way of reading both stdout and stderr from a Process. A thread-per-stream is the way to go, even though it is slightly annoying.
这篇关于如何在Java中处理多个流?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!