Is it possible to read the initial stream of an InputStream process in a NIO ByteBuffer?

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();
// other stuff omitted for brevity

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);

      // 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();
    }
  }
}
+5
source share
3 answers

, , , -

ByteArrayOutputStream ostream = new ByteArrayOutputStream(<some large number>);
WritableByteChannel destination = Channels.newChannel(ostream);

,

ostream.toByteArray() 

. , ,

ByteBuffer.wrap(ostream.toByteArray())

, runnable, , . StreamConsumer Callable<ByteBuffer>.

+5

, - java . . JNA API- , epoll Linux, kqueue/kevent MacOS X IO Completion Ports Windows.

NuProcess :

https://github.com/brettwooldridge/NuProcess

+4

, StreamConsumer .

Another blocking option that you can try may be to use a Guava ListenableFuture that provides successful and fault-tolerant calls without your own errors.

+1
source

All Articles