Home Tutorial Java Corejava Nio Creates a view of byte buffer as a char buffer.

 
 

Share on Google+Share on Google+
Creates a view of byte buffer as a char buffer.
Posted on: July 27, 2010 at 12:00 AM
Advertisement
In this tutorial you will see how to creates a view of byte buffer as a char buffer.

Creates a view of byte buffer as a char buffer.

 In this tutorial, we will see how to creates a view of this byte buffer as a char buffer.

ByteBuffer API:

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

Return type Method Description
static ByteBuffer allocate(int capacity)  The allocate(...)method allocate a new byte buffer.
abstract Charbuffer asCharBuffer() The asCharBuffer() method creates a view of byte buffer as a char buffer.
int limit() The limit() method returns the limit of associated buffer.
int position() The position() method returns the position of associated buffer.
final int capacity() The capacity() method returns the capacity of associated buffer.

code

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.DoubleBuffer;

public class AsCharBuffer {

  public static void main(String[] args) {
    File fileName = new File("bharat.txt");
    FileOutputStream outStream = null;
    try {
      outStream = new FileOutputStream(fileName, true);
    catch (FileNotFoundException e) {
      System.out.println("File not found Error.");
    }
    ByteBuffer byteBuf = ByteBuffer.allocate(256);
  System.out.println("\nInformation related to byte buffer :");
System.out.printf(" Limit = %4d position = %2d   capacity = %4d%n",
        byteBuf.limit(), byteBuf.position(), byteBuf.capacity());

    CharBuffer charBuf = byteBuf.asCharBuffer();
System.out.println("Information related to Char buffer :");
System.out.printf(" Limit = %4d  position = %2d  capacity = %4d%n",
        charBuf.limit(), charBuf.position(), charBuf.capacity());
    try {
      outStream.close();
    catch (IOException ioe) {
      System.out.println("IOException is " + ioe);
    }
  }
}

Output

C:\>java AsCharBuffer
Information related to byte buffer :
Limit = 256 position = 0 capacity = 256
Information related to char buffer :
Limit = 128 position = 0 capacity = 128

Download this code

Advertisement

Related Tags for Creates a view of byte buffer as a char buffer.:


Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.

Posted on: July 27, 2010

Recommend the tutorial

Advertisements Advertisements
 

 

 

DMCA.com