ByteBuffer asCharBuffer() method in Java

Java 8ProgrammingObject Oriented Programming

A view of the ByteBuffer can be created as a CharBuffer using the asCharBuffer() method in the class java.nio.ByteBuffer. This method requires no parameters and it returns a char buffer as required. This buffer reflects the changes made to the original buffer and vice versa.

A program that demonstrates this is given as follows −

Example

 Live Demo

import java.nio.*;
import java.util.*;
public class Demo {
   public static void main(String[] args) {
      int n = 50;
      try {
         ByteBuffer bufferB = ByteBuffer.allocate(n);
         CharBuffer bufferC = bufferB.asCharBuffer();
         bufferC.put('A');
         bufferC.put('P');
         bufferC.put('P');
         bufferC.put('L');
         bufferC.put('E');
         bufferC.rewind();
         char c;
         System.out.print("The CharBuffer is: ");
         while ((c = bufferC.get()) != 0) {
            System.out.print(c + " ");
         }
      } catch (IllegalArgumentException e) {
         System.out.println("Error!!! IllegalArgumentException");
      } catch (ReadOnlyBufferException e) {
         System.out.println("Error!!! ReadOnlyBufferException");
      }
   }
}

Output

The CharBuffer is: A P P L E
raja
Updated on 30-Jul-2019 22:30:25

Advertisements