Code example for ByteBuffer

Methods: array, capacity, limit, position, put, remaining

0
                System.out.println(String.format("Attempted to grow stream to %s bytes",
                                                 minCapacity));
                throw e;
            } 
        } 
        assert buffer.capacity() >= minCapacity : String.format("Need: %s, required %s more bytes ",
                                                                minCapacity,
                                                                minCapacity
                                                                        - buffer.remaining());
    } 
 
    /** 
     * Increases the capacity to ensure that it can hold at least the number of 
     * elements specified by the minimum capacity argument. 
     *  
     * @param minCapacity 
     *            the desired minimum capacity 
     */ 
    private void grow(int minCapacity) {
        if (buffer.capacity() >= minCapacity) {
            buffer.limit(minCapacity);
            return; 
        } 
        // overflow-conscious code 
        int oldCapacity = buffer.capacity();
        int newCapacity = oldCapacity << 1;
        if (newCapacity - minCapacity < 0)
            newCapacity = minCapacity;
        if (newCapacity < 0) {
            if (minCapacity < 0) // overflow
                throw new OutOfMemoryError("Math overflow!");
            newCapacity = Integer.MAX_VALUE;
        } 
        assert newCapacity >= minCapacity : "Math is hard";
        int position = buffer.position();
        ByteBuffer oldBuffer = buffer;
        buffer = bufferPool.allocate(newCapacity);
        buffer.put(oldBuffer.array(), 0, position);
        bufferPool.free(oldBuffer);
        assert buffer.capacity() >= minCapacity : "Math is hard";
    } 
 
    /** 
     * Writes the specified byte to this byte buffer output stream. 
     *