ByteBuffer.compact

Compacts this buffer&nbsp;&nbsp;<i>(optional operation)</i>.

<p> The bytes between the buffer's current position and its limit, if any, are copied to the beginning of the buffer. That is, the byte at index <i>p</i>&nbsp;=&nbsp;<tt>position()</tt> is copied to index zero, the byte at index <i>p</i>&nbsp;+&nbsp;1 is copied to index one, and so forth until the byte at index <tt>limit()</tt>&nbsp;-&nbsp;1 is copied to index <i>n</i>&nbsp;=&nbsp;<tt>limit()</tt>&nbsp;-&nbsp;<tt>1</tt>&nbsp;-&nbsp;<i>p</i>. The buffer's position is then set to <i>n+1</i> and its limit is set to its capacity. The mark, if defined, is discarded.

<p> The buffer's position is set to the number of bytes copied, rather than to zero, so that an invocation of this method can be followed immediately by an invocation of another relative <i>put</i> method. </p>

More...
class ByteBuffer
abstract
compact
()

Detailed Description

<p> Invoke this method after writing data from a buffer in case the write was incomplete. The following loop, for example, copies bytes from one channel to another via the buffer <tt>buf</tt>:

<blockquote><pre>{@code buf.clear(); // Prepare buffer for use while (in.read(buf) >= 0 || buf.position != 0) { buf.flip(); out.write(buf); buf.compact(); // In case of partial write } }</pre></blockquote>

@return This buffer

@throws ReadOnlyBufferException If this buffer is read-only

Meta