Use of getChar method of ByteBuffer Class in java.


 

Use of getChar method of ByteBuffer Class in java.

In this tutorial you will see the use of getChar method of ByteBuffer Class in java.

In this tutorial you will see the use of getChar method of ByteBuffer Class in java.

Use of getChar method of ByteBuffer Class in java.

In this tutorial, we will discuss the use of getChar() method of ByteBuffer class to fetch the character.

        In the given example, we will see how to get characters from byte buffer.
The put() method of ByteBuffer class write bytes into buffer, and the getChar() method of 
ByteBuffer class returns the character at current position and increment the position by two bytes.

About ByteBuffer API:

The java.nio.ByteBuffer class extends java.nio.Buffer class. It provides the following methods:

Return type Method Description
abstract CharBuffer asCharBuffer()    The asCharBuffer() method create a view of associated buffer as char buffer.
ByteBuffer put() The put() method write bytes into associated buffer.
abstract char getChar() The getChar(.) method returns character from byte buffer. 

code

import java.io.*;
import java.nio.*;
import java.nio.ByteBuffer;

public class GetChBuffer {
public static final int size = 1024;
public static void main(String[] argsthrows Exception{
    ByteBuffer bytebuf = ByteBuffer.allocate(size);
    bytebuf.asCharBuffer().put("Bharat Singh");
    char c;
  System.out.print("Character available in buffer : ");
    while ((c = bytebuf.getChar()) != 0) {
      System.out.print(c);
    }
  }
}

output

C:\>java GetChBuffer
Character available in buffer : Bharat Singh

Download this code

Ads