Java ByteBuffer Concatenate concat(ByteBuffer b1, ByteBuffer b2)

Here you can find the source of concat(ByteBuffer b1, ByteBuffer b2)

Description

Allocates a new ByteBuffer with a capacity of the sum of the ByteBuffer#limit() of the two given ByteBuffers and cancatinates them together.

License

Open Source License

Parameter

Parameter Description
b1 a parameter
b2 a parameter

Declaration

public static ByteBuffer concat(ByteBuffer b1, ByteBuffer b2) 

Method Source Code

//package com.java2s;
/**//ww w . j  ava 2  s.  co  m
 * Created on June 29, 2009.
 *
 * Copyright 2010- The MITRE Corporation. All rights reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License"); you  may not 
 * use this file except in compliance with the License. You may obtain a copy of 
 * the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software 
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 
 * License for the specific language governing permissions andlimitations under
 * the License.
 *
 * $Id$
 */

import java.nio.ByteBuffer;

public class Main {
    /**
     * Allocates a new ByteBuffer with a capacity of the sum of the <b>{@link ByteBuffer#limit()}</b> 
     * of the two given ByteBuffers and cancatinates them together.
     * If a limit is not set, then {@link ByteBuffer#capacity()} will be used. 
     * Also if one buffer is directly allocated, then the returning buffer will be directly allocated.
     * 
     * @param b1
     * @param b2
     * @return
     */
    public static ByteBuffer concat(ByteBuffer b1, ByteBuffer b2) {
        int capacity = ((b1.limit() == 0 ? b1.capacity() : b1.limit()))
                + ((b2.limit() == 0 ? b2.capacity() : b2.limit()));
        ByteBuffer dst;
        if (b1.isDirect() || b2.isDirect()) {
            dst = ByteBuffer.allocateDirect(capacity);
        } else {
            dst = ByteBuffer.allocate(capacity);
        }
        b1.rewind();
        dst.put(b1);
        b2.rewind();
        dst.put(b2);
        return dst;
    }
}

Related

  1. concat(byte[] pre, ByteBuffer bbuf)
  2. concat(ByteBuffer outPart1, ByteBuffer outPart2)
  3. concat(ByteBuffer[] buf1, ByteBuffer[] buf2)
  4. concat(ByteBuffer[] buffers, ByteBuffer buffer)
  5. concat(ByteBuffer[] buffers, int overAllCapacity)