Example of CharBuffer in Java
November 15, 2013
CharBuffer is an abstract class of the java.nio package. CharBuffer is the buffer for characters. CharBuffer object is created by calling allocate(). We need to pass the capacity of CharBuffer to allocate method.
CharBuffer chbuff = CharBuffer.allocate(1024);
CharBufferTest.java
package com.concretepage.nio; import java.io.BufferedReader; import java.io.FileInputStream; import java.io.InputStreamReader; import java.io.Reader; import java.nio.CharBuffer; public class CharBufferTest { public static void main(String[] args) { try { Reader rd = new BufferedReader(new InputStreamReader(new FileInputStream("C:/temp/test.txt"))); CharBuffer chbuff = CharBuffer.allocate(1024); while(rd.read(chbuff) > 0){ chbuff.flip(); while(chbuff.hasRemaining()){ char ch = chbuff.get(); System.out.print(ch); } chbuff.clear(); } rd.close(); } catch (Exception e) { e.printStackTrace(); } } }
CharBuffer.get(): reads the character.
CharBuffer.clear(): position becomes zero and limit is set to capacity.