Java ByteBuffer to Byte Array asByteArray(ByteBuffer buf)

Here you can find the source of asByteArray(ByteBuffer buf)

Description

Gets the content of the ByteBuffer as a byte[] without mutating the buffer (so thread safe) and minimizing GC (i.e.

License

Open Source License

Declaration

public static byte[] asByteArray(ByteBuffer buf) 

Method Source Code

//package com.java2s;
/**/*w  w w  .  j a v  a  2 s  . c om*/
 * Copyright 2007-2016, Kaazing 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 and
 * limitations under the License.
 */

import java.nio.ByteBuffer;

public class Main {
    /**
     * Gets the content of the ByteBuffer as a byte[] without mutating the buffer
     * (so thread safe) and minimizing GC (i.e. object creation)
     */
    public static byte[] asByteArray(ByteBuffer buf) {
        byte[] result;
        if (buf.hasArray() && buf.arrayOffset() == 0
                && buf.capacity() == buf.remaining()) {
            result = buf.array();
        } else {
            result = new byte[buf.remaining()];
            if (buf.hasArray()) {
                System.arraycopy(buf.array(),
                        buf.arrayOffset() + buf.position(), result, 0,
                        result.length);
            } else {
                // Direct buffer
                ByteBuffer duplicate = buf.duplicate();
                duplicate.mark();
                duplicate.get(result);
                duplicate.reset();
            }
        }
        return result;
    }
}

Related

  1. asByteArray(ByteBuffer buf)
  2. byteBufferToByteArray(ByteBuffer buf)
  3. ByteBufferToByteArray(ByteBuffer byteBuffer)
  4. byteBufferToByteArray(ByteBuffer byteBuffer)