Copies the contents in the specified ByteBuffer , but not any of its attributes (e.g. - Java java.nio

Java examples for java.nio:ByteBuffer

Description

Copies the contents in the specified ByteBuffer , but not any of its attributes (e.g.

Demo Code


//package com.java2s;
import java.nio.ByteBuffer;

public class Main {
    /**//w ww.  j  a v a2 s .  co m
     * Copies the contents in the specified {@link ByteBuffer}, but <strong>not</strong> any of its attributes (e.g.
     * mark, read-only). The capacity and limit of the new buffer will be the limit of the specified one, the position
     * of the new buffer will be 0, and the mark will be undefined. The specified buffer will be flipped after writing.
     * <p>
     * This method uses {@link ByteBuffer#put(ByteBuffer)} and so will write from the specified byte buffers current
     * position.
     *
     * @param buffer The byte buffer.
     * @return The copied byte buffer.
     */
    public static ByteBuffer copy(ByteBuffer buffer) {
        ByteBuffer copy = ByteBuffer.allocate(buffer.limit());
        copy.put(buffer).flip();
        buffer.flip();
        return copy;
    }
}

Related Tutorials