Reading a file through Java BufferedReader

java.io.BufferedReader reads text from a character-input stream, buffering characters so as to provide for the efficient reading of characters, arrays, and lines.

With BufferReader, each read request made of a Reader causes a corresponding read request to be made of the underlying character or byte stream.  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.
Below is the sample illustrates use of java.io.BufferedReader :

package org.techmeonline.samples;

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

public class BufferedReaderSample {

public static void main(String[] args) {

BufferedReader bufferReader = null;

try {

String strCurrentLine;
System.out.println(“Start of File Content***********”);

bufferReader = new BufferedReader(new FileReader(“C:\\techmesample.txt”));

while ((strCurrentLine = bufferReader .readLine()) != null) {
System.out.println(strCurrentLine);
}

} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (bufferReader != null) {
bufferReader.close();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
System.out.println(“End of File Content***********”);

}
}

Leave a Reply

Your email address will not be published. Required fields are marked *