Is it possible to use NIO to handle stdout from a process? I have work with java.io, but it's a bit of an exercise to learn a little about NIO and explore the possibility of improving performance.
Basically, I want to transfer a large amount of text from stdout to the buffer without blocking as soon as possible, and then process the contents of this buffer later. The trouble is that I cannot figure out the correct voodoo for it to work with NIO. This is where I am now:
ProcessBuilder pb = new ProcessBuilder( ... );
Process p = pb.start();
stdout = new StreamConsumer(p.getInputStream());
new Thread(stdout).start();
The StreamConsumer class is as follows:
class StreamConsumer implements Runnable
{
private InputStream is;
public StreamConsumer(InputStream is)
{
this.is = is;
}
public void run()
{
try
{
ReadableByteChannel source = Channels.newChannel(is);
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();
}
}
}
source
share