Code example for ByteBuffer

Methods: clear, compact, hasRemaining, remaining

0
    /** 
     * Sets input mode. The buffer can now be written into. 
     */ 
    protected void setInputMode() { 
        if (this.mode != INPUT_MODE) {
            if (this.buffer.hasRemaining()) {
                this.buffer.compact();
            } else { 
                this.buffer.clear();
            } 
            this.mode = INPUT_MODE;
        } 
    } 
 
    private void expandCapacity(final int capacity) {
        final ByteBuffer oldbuffer = this.buffer;
        this.buffer = allocator.allocate(capacity);
        oldbuffer.flip();
        this.buffer.put(oldbuffer);
    } 
 
    /** 
     * Expands buffer's capacity. 
     */ 
    protected void expand() { 
        int newcapacity = (this.buffer.capacity() + 1) << 1;
        if (newcapacity < 0) {
            newcapacity = Integer.MAX_VALUE;
        } 
        expandCapacity(newcapacity);
    } 
 
    /** 
     * Ensures the buffer can accommodate the required capacity. 
     */ 
    protected void ensureCapacity(final int requiredCapacity) {
        if (requiredCapacity > this.buffer.capacity()) {
            expandCapacity(requiredCapacity);
        } 
    } 
 
    /** 
     * Returns the total capacity of this buffer. 
     * 
     * @return total capacity. 
     */ 
    public int capacity() { 
        return this.buffer.capacity();
    } 
 
    /** 
     * Determines if the buffer contains data. 
     * 
     * @return <code>true</code> if there is data in the buffer, 
     *   <code>false</code> otherwise. 
     */ 
    public boolean hasData() { 
        setOutputMode(); 
        return this.buffer.hasRemaining();
    } 
 
    /** 
     * Returns the length of this buffer. 
     * 
     * @return buffer length. 
     */ 
    public int length() { 
        setOutputMode(); 
        return this.buffer.remaining();
    } 
 
    /** 
     * Returns available capacity of this buffer. 
     * 
     * @return buffer length. 
     */ 
    public int available() { 
        setInputMode(); 
        return this.buffer.remaining();
    } 
 
    /** 
     * Clears buffer. 
     */