duplicate ByteBuffer And Merge - Java java.nio

Java examples for java.nio:ByteBuffer

Description

duplicate ByteBuffer And Merge

Demo Code


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

public class Main {
    static ByteBuffer duplicateAndMerge(ByteBuffer[] buffers) {

        if (buffers.length == 0) {
            return ByteBuffer.allocate(0);

        } else if (buffers.length == 1) {
            return buffers[0].duplicate();

        } else {/*from   w w w.  j av  a  2s.  c o m*/
            int size = 0;
            for (ByteBuffer byteBuffer : buffers) {
                if (byteBuffer != null) {
                    size += byteBuffer.remaining();
                }
            }

            ByteBuffer buffer = ByteBuffer.allocate(size);
            for (ByteBuffer byteBuffer : buffers) {
                if (byteBuffer != null) {
                    int pos = byteBuffer.position();
                    int limit = byteBuffer.limit();
                    buffer.put(byteBuffer);

                    byteBuffer.position(pos);
                    byteBuffer.limit(limit);
                }
            }

            buffer.flip();
            return buffer;
        }
    }
}

Related Tutorials