Example usage for java.nio ByteBuffer allocate

List of usage examples for java.nio ByteBuffer allocate

Introduction

In this page you can find the example usage for java.nio ByteBuffer allocate.

Prototype

public static ByteBuffer allocate(int capacity) 

Source Link

Document

Creates a byte buffer based on a newly allocated byte array.

Usage

From source file:com.talent.nio.communicate.receive.DecodeRunnable.java

/**
 * @param args//from   w w  w .j  a v a2 s .  c om
 */
public static void main(String[] args) {
    byte[] bs1 = new byte[] { 1, 10, 11, 12 };
    byte[] bs2 = new byte[] { 2, 2, 2, 2 };
    byte[] bs3 = new byte[] { 3, 3, 3, 3 };
    byte[] bs4 = new byte[] { 4, 4, 4, 4 };
    byte[] bs5 = new byte[] { 5, 5, 5, 5 };
    byte[] bs6 = new byte[] { 6, 6, 6, 6 };

    ByteBuffer buffer1 = ByteBuffer.allocate(1024);
    buffer1.put(bs1);
    buffer1.flip();

    ByteBuf buf1 = Unpooled.copiedBuffer(buffer1);// .copiedBuffer(bs1);

    buffer1.put(bs3);

    ByteBuf buf2 = Unpooled.copiedBuffer(bs2);
    ByteBuf buf3 = Unpooled.copiedBuffer(bs3);
    ByteBuf buf4 = Unpooled.copiedBuffer(bs4);
    ByteBuf buf5 = Unpooled.copiedBuffer(bs5);
    ByteBuf buf6 = Unpooled.copiedBuffer(bs6);

    CompositeByteBuf cb = Unpooled.compositeBuffer();
    cb.addComponents(buf1, buf2, buf3);

    byte dd = cb.getByte(0);

    CompositeByteBuf cb2 = Unpooled.compositeBuffer();
    cb.addComponents(buf4, buf5, buf6);

    // cb.c
    // cb2.writerIndex(128 * 1024);

    cb.addComponent(cb2);

    Long number = cb2.readLong(); // causes IllegalBufferAccessException
                                  // here!

}

From source file:Main.java

public static String processRead(SelectionKey key) throws Exception {
    SocketChannel sChannel = (SocketChannel) key.channel();
    ByteBuffer buffer = ByteBuffer.allocate(1024);
    sChannel.read(buffer);/*ww w. ja  va  2 s  . co  m*/
    buffer.flip();
    Charset charset = Charset.forName("UTF-8");
    CharsetDecoder decoder = charset.newDecoder();
    CharBuffer charBuffer = decoder.decode(buffer);
    String msg = charBuffer.toString();
    return msg;
}

From source file:com.log4ic.compressor.utils.FileUtils.java

/**
 * ?//from ww w.j  a v  a 2  s.com
 *
 * @param content
 * @param filePath
 * @return
 */
public static File writeFile(byte[] content, String filePath) {
    FileOutputStream out = null;
    FileChannel outChannel = null;
    File file = new File(filePath);

    if (file.exists()) {
        file.delete();
    }

    if (!file.getParentFile().exists()) {
        file.getParentFile().mkdirs();
    }

    ByteBuffer outBuffer = ByteBuffer.allocate(content.length);
    outBuffer.put(content);
    outBuffer.flip();
    try {
        out = new FileOutputStream(file);

        outChannel = out.getChannel();

        outChannel.write(outBuffer);

    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (outChannel != null) {
            try {
                outChannel.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        if (out != null) {
            try {
                out.flush();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                out.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    return file.exists() ? file : null;
}

From source file:com.offbynull.portmapper.common.ByteBufferUtils.java

/**
 * Copy the remaining content of a {@link ByteBuffer} in to a new array.
 * @param src buffer to copy//from   w w w.ja  v  a2s  . c om
 * @param incrementSrc of {@code true} increments {@code src}'s position
 * @return new buffer with the remaining content in {@code src}
 * @throws NullPointerException if any arguments are {@code null}
 */
public static byte[] copyContentsToArray(ByteBuffer src, boolean incrementSrc) {
    Validate.notNull(src);
    if (!incrementSrc) {
        src.mark();
    }

    ByteBuffer dst = ByteBuffer.allocate(src.remaining());
    dst.put(src);

    if (!incrementSrc) {
        src.reset();
    }

    return dst.array();
}

From source file:crocserver.app.CrocSecurity.java

private static byte[] toByteArray(long value) {
    ByteBuffer buffer = ByteBuffer.allocate(8);
    buffer.putLong(value);/*  www . ja va2 s . c o m*/
    return buffer.array();
}

From source file:de.rwhq.serializer.FixedStringSerializer.java

@Override
public byte[] serialize(final String o) {
    final byte[] bytes = o.getBytes();

    if (bytes.length > (length - 1)) {
        throw new IllegalArgumentException("String is too long to be serialized");
    }//  w w w . ja va 2 s. c om

    final ByteBuffer buf = ByteBuffer.allocate(length);
    buf.putShort((short) bytes.length);
    buf.put(bytes);
    return buf.array();
}

From source file:com.datatorrent.contrib.hdht.HDHTDynamicPartitioningTest.java

static Slice getLongByteArray(long key) {
    ByteBuffer bb = ByteBuffer.allocate(8);
    bb.putLong(key);
    return new Slice(bb.array());
}

From source file:com.github.neoio.net.message.staging.memory.TestMemoryMessageStaging.java

@Test
public void test_tempRead() {
    ByteBuffer buffer = ByteBuffer.allocate(1024);

    buffer.put("Hello World".getBytes());
    buffer.rewind();/*from  w  w  w  . java  2 s.c om*/
    staging.writeTempReadBytes(buffer);
    Assert.assertTrue(staging.hasTempReadBytes());

    buffer.clear();
    staging.readTempReadBytes(buffer);
    Assert.assertEquals("Hello World",
            new String(ArrayUtils.subarray(buffer.array(), 0, "Hello World".getBytes().length)));
    staging.resetTempReadBytes();

    Assert.assertFalse(staging.hasTempReadBytes());
}

From source file:com.aerohive.nms.engine.admin.task.licensemgr.license.processor2.PacketUtil.java

public static byte[] join(Header header, byte[] content) {
    ByteBuffer buf = ByteBuffer.allocate(8192);

    byte[] outBytes;
    if (content.length == 0) {
        outBytes = new byte[0];
    } else {/*from   w w w.  ja v a2s.com*/
        if (header.isSecretFlag()) {
            // encrypt data
            outBytes = encryptData(content);
        } else {
            outBytes = new byte[content.length];
            System.arraycopy(content, 0, outBytes, 0, content.length);
        }
    }
    buf.put(header.getType());
    buf.putInt(outBytes.length);
    buf.put(header.getProtocolVersion());
    buf.put(header.isSecretFlag() ? CommConst.Secret_Flag_Yes : CommConst.Secret_Flag_No);
    buf.put(outBytes);

    buf.flip();

    byte[] dst = new byte[buf.limit()];
    buf.get(dst);
    return dst;
}

From source file:Main.java

public static final ByteBuffer borrowByteBuffer(final int capacity) {
    if (capacity >= MAX_LINE_BYTES_VERY_LARGE) {
        return ByteBuffer.allocate(capacity);
    } else if (capacity >= MAX_LINE_BYTES_LARGE) {
        return borrowByteBufferVeryLarge();
    } else if (capacity >= MAX_LINE_BYTES_MEDIUM) {
        return borrowByteBufferLarge();
    } else if (capacity >= MAX_LINE_BYTES_NORMAL) {
        return borrowByteBufferMedium();
    } else if (capacity >= MAX_LINE_BYTES_SMALL) {
        return borrowByteBufferNormal();
    } else {//from  w  ww .  java  2  s  .com
        return borrowByteBufferSmall();
    }
}