Java Code Example for BufferedReader to read Character InputStream

BufferedReader class of Java API provides a way to read the character inputstream, by buffering the characters which provides an efficient way to read the characters, arrays and lines.

The buffer size may be specified, or the default size may be used. The default is large enough for most purposes.

In general, each read request made of a Reader causes a corresponding read request to be made of the underlying character or byte stream. It is therefore advisable to wrap a BufferedReader around any Reader whose read() operations may be costly, such as FileReaders and InputStreamReaders. For example,

 BufferedReader in    = new BufferedReader(new FileReader("foo.in"));

will buffer the input from the specified file. Without buffering, each invocation of read() or readLine() could cause bytes to be read from the file, converted into characters, and then returned, which can be very inefficient.

Programs that use DataInputStreams for textual input can be localized by replacing each DataInputStream with an appropriate BufferedReader.


/**********************************************************************************
 * Created on Nov, 2004 Copyright(c) https://kodehelp.com All Rights Reserved. 
 **********************************************************************************/
package com.kodehelp.java.io.BufferedReader;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

/**
 * @author https://kodehelp.com
 *
 */
public class BufferedReaderExample {
	/**
	 * @param args
	 * @throws IOException 
	 */
	public static void main(String[] args) throws IOException {
		BufferedReader reader=null;
	try{
		reader = new BufferedReader(new FileReader("/test.txt"));
		String line;
		while((line=reader.readLine())!=null){
			System.out.println(line);
		}
	}catch(Exception ex){
		ex.printStackTrace();
	}finally{
		if(reader!=null)
		reader.close();	
	}
	}
}