How to get bytes from ByteBuffer in java.


 

How to get bytes from ByteBuffer in java.

In this tutorial you will see how to get bytes from ByteBuffer in java.

In this tutorial you will see how to get bytes from ByteBuffer in java.

How to get bytes from ByteBuffer in java.

                      In this tutorial, we will discuss how to get bytes from buffer. The ByteBuffer 
class is a container for handling data. The method allocate( int capacity) creates a new byte 
buffer, and the current position will be zero and its limit will be it's capacity. The FileChannel 
class creates a channel for reading, writing,  mapping  and manipulating a file. The FileChannel
 is similar to the stream but they are few different. The channel can read write bot, but stream can 
either read-only or write-only. The getChannel method of FileInputStream class returns the 
Channel object associated with this file input stream. The read() method of FileChannel class 
fills byte buffer created by using allocate() method. The get() method of ByteBuffer class 
reads bytes of from  buffer's current  position and increment position. 

About 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 create a byte buffer of specified capacity. 
byte get() The get() method reads bytes of from  buffer's current position and increment position. 

code

import java.io.*;
import java.nio.*;
import java.io.FileInputStream;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

public class JavaByteBuffer {
public static void main(String[] argsthrows Exception {
FileInputStream finStream = new FileInputStream(args[0]);
    System.out.println("Given file name :" + args[0]);
    FileChannel fchannel = finStream.getChannel();
    ByteBuffer bytebuf = ByteBuffer.allocate(1024);
    fchannel.read(bytebuf);
    bytebuf.flip();
    System.out.print("Contents of file ");
    while (bytebuf.hasRemaining()) {
      System.out.print((charbytebuf.get());
    }

  }
}

Output:

C:\>java JavaByteBuffer C:\Work\Bharat\NIO\byteBuffer\test.txt
Given file name :C:\Work\Bharat\NIO\byteBuffer\test.txt
Contents of file
roseindia

Download this code

Ads