Friday 7 June 2019

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.

Test.java
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);
 }
}


Output
Data : HELLO WORLD



Previous                                                 Next                                                 Home

No comments:

Post a Comment