In our previous example I have explained about the FileReader. FileReader is useful for reading the text content by characters. This is slow in performance when using for the huge files. BufferedReader is buffering the text for Reader’s. Buffering will speed up the IO operation. Instead of reading one character at a time using the FileReader, BufferedReader will be fast for reading the huge amount of data. Also it helps you to read the text file line by line.
The main difference between BufferedReader and BufferedInputStream is that Reader’s work on characters (text), wheres InputStream’s works on raw bytes. Each API can be chosen for the suitable scenarios.
Lets look at the below example. We need to wrap the FileReader into the BufferedReader to read a text file.
BufferedReaderExample.java
package javabeat.net.core; import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; /** * File BufferedReader Example * * @author Krishna * */ public class BufferedReaderExample { public static void main(String args[]) { FileReader fileReader = null; BufferedReader bufferedReader = null; String str = null; try { fileReader = new FileReader("TextFile.txt"); bufferedReader = new BufferedReader(fileReader); while ((str = bufferedReader.readLine()) != null) { System.out.println(str); } bufferedReader.close(); } catch (FileNotFoundException exception) { exception.printStackTrace(); } catch (IOException exception) { exception.printStackTrace(); } } }
TextFile.txt
Reading the text content using BufferedReader!!
Output…
Reading the text content using BufferedReader!!