Java ByteBuffer Create createByteBuffer(byte... data)

Here you can find the source of createByteBuffer(byte... data)

Description

create Byte Buffer

License

Open Source License

Declaration

public static ByteBuffer createByteBuffer(byte... data) 

Method Source Code


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

import java.util.Collections;
import java.util.Map;
import java.util.WeakHashMap;

public class Main {
    private static final Map<Buffer, Object> trackingHash = Collections
            .synchronizedMap(new WeakHashMap<Buffer, Object>());
    private static final Object ref = new Object();
    private static final boolean trackDirectMemory = false;

    /**//from  w  w  w. j a  v a 2  s.c  o m
     * Create a new ByteBuffer of the specified size.
     *
     * @param size
     *            required number of ints to store.
     * @return the new IntBuffer
     */
    public static ByteBuffer createByteBuffer(int size) {
        ByteBuffer buf = ByteBuffer.allocateDirect(size).order(ByteOrder.nativeOrder());
        buf.clear();
        if (trackDirectMemory) {
            trackingHash.put(buf, ref);
        }
        return buf;
    }

    /**
     * Create a new ByteBuffer of an appropriate size to hold the specified
     * number of ints only if the given buffer if not already the right size.
     *
     * @param buf
     *            the buffer to first check and rewind
     * @param size
     *            number of bytes that need to be held by the newly created
     *            buffer
     * @return the requested new IntBuffer
     */
    public static ByteBuffer createByteBuffer(ByteBuffer buf, int size) {
        if (buf != null && buf.limit() == size) {
            buf.rewind();
            return buf;
        }

        buf = createByteBuffer(size);
        return buf;
    }

    public static ByteBuffer createByteBuffer(byte... data) {
        ByteBuffer bb = createByteBuffer(data.length);
        bb.put(data);
        bb.flip();
        return bb;
    }

    public static ByteBuffer createByteBuffer(String data) {
        byte[] bytes = data.getBytes();
        ByteBuffer bb = createByteBuffer(bytes.length);
        bb.put(bytes);
        bb.flip();
        return bb;
    }
}

Related

  1. allocaleByteBuffer(int capacity, boolean direct)
  2. allocateByteBuffer(boolean useDirectBuffer, int bufSize)
  3. allocateByteBuffer(final int bytes)
  4. allocateByteBuffer(int capacity)
  5. createByteBuffer(byte... values)
  6. createByteBuffer(byte[] data)
  7. createByteBuffer(int byteCount)
  8. createByteBuffer(int capacity)