Java NIO and Java 8 provide many new ways to read a file in Java, like using Scanner to read file in Java or Reading File in Java 8 but reading a file in Java using BufferedReader still remains one of the most used way.
The advantage of using buffered I/O streams for reading/writing file in Java is that each request doesn't trigger disk access or network activity.
When buffered input stream is used to read a file in Java data is read from a memory area known as a buffer; the native input API is called only when the buffer is empty.
In case of buffered output stream data is written to a buffer, and the native output API is called only when the buffer is full.
Java Program to read a file using BufferedReader
In the program readLine() method of the BufferedReader class is used to read the file. This method reads data from file one line at a time. A line is considered to be terminated by any one of a line feed ('\n'), a carriage return ('\r'), or a carriage return followed immediately by a linefeed.
import java.io.BufferedReader; import java.io.IOException; public class FileRead { public static void main(String[] args) { BufferedReader br = null; try{ String strLine; // Instance of FileReader wrapped in a BufferedReader br = new BufferedReader(new java.io.FileReader("F:\\abc.txt")); // Read lines from the file, returns null when end of stream // is reached while((strLine = br.readLine()) != null){ System.out.println("Line is - " + strLine); } }catch(IOException ioExp){ System.out.println("Error while reading file " + ioExp.getMessage()); }finally { try { // Close the stream if(br != null){ br.close(); } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } }
Output
Line is - This is a test file. Line is - BuferedReader is used to read this file.
Using BufferedReader With try-with-resources
If you are using Java 7 or above you can use try-with-resources for automatic resource management while reading file using BufferedReader. In that case you don't have to explicitly close the resources using try-catch Block. Resources (in this case stream) will be closed automatically after the program is finished with it.
Resource will be declared with the try statement itself when using try-with-resources.
import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; public class FileRead { public static void main(String[] args) { try(BufferedReader br = new BufferedReader(new FileReader("F://abc.txt"))){ String strLine; // Read lines from the file, returns null when end of stream // is reached while((strLine = br.readLine()) != null){ System.out.println("Line is - " + strLine); } }catch(IOException ioExp){ System.out.println("Error while reading file " + ioExp.getMessage()); } } }
That's all for this topic Reading File in Java Using BufferedReader. If you have any doubt or any suggestions to make please drop a comment. Thanks!
>>>Return to Java Programs Page
Related Topics
You may also like-