Java examples for java.nio:ByteBuffer
Flip the ByteBuffer to fill mode.
//package com.java2s; import java.nio.ByteBuffer; public class Main { /** Flip the buffer to fill mode. * The position is set to the first unused position in the buffer * (the old limit) and the limit is set to the capacity. * If the buffer is empty, then this call is effectively {@link #clearToFill(ByteBuffer)}. * If there is no unused space to fill, a {@link ByteBuffer#compact()} is done to attempt * to create space.//from w w w. j av a 2s . c o m * <p> * This method is used as a replacement to {@link ByteBuffer#compact()}. * * @param buffer The buffer to flip * @return The position of the valid data before the flipped position. This value should be * passed to a subsequent call to {@link #flipToFlush(ByteBuffer, int)} */ public static int flipToFill(ByteBuffer buffer) { int position = buffer.position(); int limit = buffer.limit(); if (position == limit) { buffer.position(0); buffer.limit(buffer.capacity()); return 0; } int capacity = buffer.capacity(); if (limit == capacity) { buffer.compact(); return 0; } buffer.position(limit); buffer.limit(capacity); return position; } /** Compact the buffer * @param buffer the buffer to compact * @return true if the compact made a full buffer have space */ public static boolean compact(ByteBuffer buffer) { boolean full = buffer.limit() == buffer.capacity(); buffer.compact().flip(); return full && buffer.limit() < buffer.capacity(); } }