Wraps data into a ByteBuffer prefixed by its length. - Java java.nio

Java examples for java.nio:ByteBuffer Int

Description

Wraps data into a ByteBuffer prefixed by its length.

Demo Code


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

public class Main {
    public static void main(String[] argv) throws Exception {
        byte[] data = new byte[] { 34, 35, 36, 37, 37, 37, 67, 68, 69 };
        System.out.println(toByteBuffer(data));
    }//from   w  w  w .j a v a2 s . c  om

    /**
     * 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 Tutorials