是否可以使用 NIO 处理来自 Process 的标准输出?我让它与 java.io 一起工作,但这是一个练习,可以更多地了解 NIO 并探索性能改进的可能性。
基本上,我想尽可能快地将大量文本从标准输出流式传输到缓冲区而不会阻塞,然后稍后处理该缓冲区的内容。问题是,我似乎无法找出正确的巫术来使它与 NIO 一起工作。这就是我现在的位置:
ProcessBuilder pb = new ProcessBuilder( ... );
Process p = pb.start();
stdout = new StreamConsumer(p.getInputStream());
new Thread(stdout).start();
// other stuff omitted for brevity
StreamConsumer 类如下所示:
class StreamConsumer implements Runnable
{
private InputStream is;
public StreamConsumer(InputStream is)
{
this.is = is;
}
public void run()
{
try
{
ReadableByteChannel source = Channels.newChannel(is);
// Is it possible get a channel to a ByteBuffer
// or MappedByteBuffer here?
WritableByteChannel destination = ??;
ByteBuffer buffer = ByteBuffer.allocateDirect(128 * 1024);
while (source.read(buffer) != -1)
{
buffer.flip();
while (buffer.hasRemaining())
{
destination.write(buffer);
}
buffer.clear();
}
source.close();
destination.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
}