Java ByteBuffer Concatenate concat(List bbs)

Here you can find the source of concat(List bbs)

Description

Concatenates one or more byte buffers to one large buffer.

License

Open Source License

Parameter

Parameter Description
bbs list of byte buffers to combine

Return

byte buffer containing the combined content of the supplied byte buffers

Declaration

public static ByteBuffer concat(List<ByteBuffer> bbs) 

Method Source Code

//package com.java2s;
//License from project: Open Source License 

import java.nio.ByteBuffer;

import java.util.Arrays;
import java.util.List;

public class Main {
    public static final ByteBuffer EMPTY = ByteBuffer.allocate(0);

    /**/*w w  w .ja v a2 s .  co m*/
     * Concatenates one or more byte buffers to one large buffer. The combined
     * size of all buffers must not exceed {@link java.lang.Integer#MAX_VALUE}.
     * 
     * @param bbs list of byte buffers to combine
     * @return byte buffer containing the combined content of the supplied byte
     *         buffers
     */
    public static ByteBuffer concat(List<ByteBuffer> bbs) {
        long length = 0;

        // get amount of remaining bytes from all buffers
        for (ByteBuffer bb : bbs) {
            bb.rewind();
            length += bb.remaining();
        }

        if (length > Integer.MAX_VALUE) {
            throw new IllegalArgumentException("Buffers are too large for concatenation");
        }

        if (length == 0) {
            // very funny
            return EMPTY;
        }

        ByteBuffer bbNew = ByteBuffer.allocateDirect((int) length);

        // put all buffers from list
        for (ByteBuffer bb : bbs) {
            bb.rewind();
            bbNew.put(bb);
        }

        bbNew.rewind();

        return bbNew;
    }

    /**
     * Concatenates one or more byte buffers to one large buffer. The combined
     * size of all buffers must not exceed {@link java.lang.Integer#MAX_VALUE}.
     * 
     * @param bb one or more byte buffers to combine
     * @return byte buffer containing the combined content of the supplied byte
     *         buffers
     */
    public static ByteBuffer concat(ByteBuffer... bb) {
        return concat(Arrays.asList(bb));
    }
}

Related

  1. concat(ByteBuffer b1, ByteBuffer b2)
  2. concat(ByteBuffer outPart1, ByteBuffer outPart2)
  3. concat(ByteBuffer[] buf1, ByteBuffer[] buf2)
  4. concat(ByteBuffer[] buffers, ByteBuffer buffer)
  5. concat(ByteBuffer[] buffers, int overAllCapacity)
  6. concatenateBytebuffers(ArrayList buffers)