javabytebuffernio

Java NIO ByteBuffer, write after flip


I'm new to Java ByteBuffers and was wondering what the correct way to write to a ByteBuffer after it has been flipped.

In my use case, I am writing an outputBuffer to a socket:

    outBuffer.flip();
    //Non-blocking SocketChannel
    int bytesWritten = getSocket().write(outBuffer);

After this, the output buffer has to be written to again. Also not all of the bytes in the outBuffer may have been written to the socket.

Since it is currently flipped, how can I make it writable again, without overriding any data if it is still in the buffer and wasn't written to the socket?

If I am right, outBuffer.position() == bytesWritten and limit should be at how much data there was to write.

So would using the following in order to reuse the output buffer be right? :

   int limit = outBuffer.limit()  
   outBuffer.limit(outBuffer.capacity());
   outBuffer.position(limit);

Solution

  • Again from the API spec.: The following loop copies bytes from one channel to another via the buffer buf:

    while (in.read(buf) >= 0 || buf.position != 0) {
       buf.flip();
       out.write(buf);
       buf.compact();    // In case of partial write
    }