Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

nio: Writing data to buffers

Every primitive buffer class provide put() methods to insert data into the buffer.

For example, Bytebuffer class provides below put methods to insert data.

public abstract ByteBuffer put(byte b);
public abstract ByteBuffer put(int index, byte b)
public ByteBuffer put(ByteBuffer src)

In the same way, CharBuffer also provides below put methods to insert data.

public abstract CharBuffer put(char c);
public abstract CharBuffer put(int index, char c);
public CharBuffer put(CharBuffer src)

‘put’ method writes the data to current position and increment the position.

Let’s see an example, how can we fill the data into ByteBuffer.

Step 1: Define ByteBuffer instance.
ByteBuffer byteBuffer = ByteBuffer.allocate(11);

Step 2: Add data to ByteBuffer.
byteBuffer.put((byte)'H').put((byte)'E').put((byte)'L').put((byte)'L').put((byte)'O').put((byte)' ').put((byte)'W').put((byte)'O').put((byte)'R').put((byte)'L').put((byte)'D');

Find the below working application.
package com.sample.nio;

import java.nio.ByteBuffer;

public class Test {

public static void main(String args[]) throws Exception {
/* Define new Byte Buffer of capacity 11 */
ByteBuffer byteBuffer = ByteBuffer.allocate(11);

/* Add elements to the byte buffer */
byteBuffer.put((byte) 'H').put((byte) 'E').put((byte) 'L').put((byte) 'L').put((byte) 'O').put((byte) ' ')
.put((byte) 'W').put((byte) 'O').put((byte) 'R').put((byte) 'L').put((byte) 'D');

/* Print the data in byteBuffer */
byte[] dataBytes = byteBuffer.array();
String dataStr = new String(dataBytes);

System.out.println("Data : " + dataStr);

This post first appeared on Java Tutorial : Blog To Learn Java Programming, please read the originial post: here

Share the post

nio: Writing data to buffers


Subscribe to Java Tutorial : Blog To Learn Java Programming

Get updates delivered right to your inbox!

Thank you for your subscription