Home  >  Core Java

Example of ByteBuffer in Java

By Arvind Rai, November 15, 2013
ByteBuffer belongs to the package java.nio. ByteBuffer has been introduced in JDK 1.4. ByteBuffer is the buffer of bytes. ByteBuffer is abstract class but it has static method .i.e. allocate() to return the ByteBuffer.
ByteBuffer byteBuffer = ByteBuffer.allocate(512);
 
Allocate method takes the capacity to read bytes at one time.

ByteBufferTest.java
package com.concretepage.nio;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
public class ByteBufferTest {
	public static void main(String[] args) {
		try{
		    RandomAccessFile rafile = new RandomAccessFile("C:/temp/test.txt", "r");
		    FileChannel fileChannel = rafile.getChannel();
		    ByteBuffer byteBuffer = ByteBuffer.allocate(512);
		    while(fileChannel.read(byteBuffer) > 0) {
		    	byteBuffer.flip();
		        while(byteBuffer.hasRemaining()){
		        	char ch = (char) byteBuffer.get();
		        	System.out.print(ch);
		        }
		        byteBuffer.clear();
		    }
		    fileChannel.close();
		    rafile.close();
		} catch (IOException e) {
	      e.printStackTrace();
        }
	}
}
 
ByteBuffer has flip() method. And whenever we call it, the limit of ByteBuffer is set to current position and position is set to zero. Calling get() method, returns the byte to be read. Calling clear() method , it clears the buffer, sets position to zero and sets limit to position.
POSTED BY
ARVIND RAI
ARVIND RAI
FIND MORE TUTORILAS






©2019 concretepage.com | Privacy Policy | Contact Us