Java ByteBuffer from Byte Array toByteBuffer(byte[] data)

Here you can find the source of toByteBuffer(byte[] data)

Description

Wraps data into a ByteBuffer prefixed by its length.

License

Open Source License

Parameter

Parameter Description
data The data to wrap

Return

The allocated ByteBuffer

Declaration

public static ByteBuffer toByteBuffer(byte[] data) 

Method Source Code


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

import java.nio.ByteBuffer;

public class Main {
    /**//  w w w .j a v a2 s . co  m
     * Wraps data into a ByteBuffer prefixed by its length.
     * If data.length > Integer.Max, the returned data will be incoherent.
     *
     * @param data The data to wrap
     * @return The allocated ByteBuffer
     */
    public static ByteBuffer toByteBuffer(byte[] data) {
        ByteBuffer bb = ByteBuffer.allocate(4 + data.length);
        bb.putInt(data.length);
        bb.put(data);
        bb.rewind();

        return bb;
    }
}

Related

  1. readBytes(ByteBuffer buffer, int length)
  2. readBytes(ByteBuffer buffer, int position, int length)
  3. readBytes(final ByteBuffer bb, final int length)
  4. toByteBuffer(byte[] array)
  5. toByteBuffer(byte[] bytes)