Share on Google+Share on Google+

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. 


import java.nio.*;
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);;
    System.out.print("Contents of file ");
    while (bytebuf.hasRemaining()) {



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

Download this code


Posted on: July 23, 2010 If you enjoyed this post then why not add us on Google+? Add us to your Circles

Share this Tutorial 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.


Advertisement null