Home  >  Core Java

Example of CharBuffer in Java

By Arvind Rai, 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);
 
Find the example of CharBuffer.

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.flip(): limit is flipped to Current position and position becomes zero.
CharBuffer.get(): reads the character.
CharBuffer.clear(): position becomes zero and limit is set to capacity.
POSTED BY
ARVIND RAI
ARVIND RAI
FIND MORE TUTORILAS






©2019 concretepage.com | Privacy Policy | Contact Us