Example of ByteBuffer in Java
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);
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(); } } }