How to Read File Line by Line in Java - Simple Guide
To read a file line by line in Java, use
BufferedReader with a FileReader. Call readLine() in a loop until it returns null, which means the file ended.Syntax
Use BufferedReader wrapped around a FileReader to read text files efficiently. The readLine() method reads one line at a time and returns null when no more lines exist.
BufferedReader br = new BufferedReader(new FileReader("filename.txt"));- opens the file.String line = br.readLine();- reads one line.while (line != null) { ... }- loops until end of file.br.close();- closes the file to free resources.
java
BufferedReader br = new BufferedReader(new FileReader("filename.txt")); String line; while ((line = br.readLine()) != null) { // process line } br.close();
Example
This example reads a file named example.txt line by line and prints each line to the console.
java
import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; public class ReadFileLineByLine { public static void main(String[] args) { try (BufferedReader br = new BufferedReader(new FileReader("example.txt"))) { String line; while ((line = br.readLine()) != null) { System.out.println(line); } } catch (IOException e) { System.err.println("Error reading file: " + e.getMessage()); } } }
Output
Hello, this is line 1.
This is line 2.
And this is line 3.
Common Pitfalls
Common mistakes include not closing the BufferedReader, which can cause resource leaks, and not handling IOException. Also, using FileReader alone without buffering can be slower for large files.
Another mistake is reading lines without checking for null, which leads to NullPointerException.
java
/* Wrong way: Not closing BufferedReader and no exception handling */ BufferedReader br = new BufferedReader(new FileReader("file.txt")); String line = br.readLine(); while (line != null) { System.out.println(line); line = br.readLine(); } /* Right way: Using try-with-resources and handling exceptions */ try (BufferedReader br = new BufferedReader(new FileReader("file.txt"))) { String line; while ((line = br.readLine()) != null) { System.out.println(line); } } catch (IOException e) { e.printStackTrace(); }
Quick Reference
- Use
BufferedReaderwithFileReaderfor efficient reading. - Always check if
readLine()returnsnullto detect end of file. - Use try-with-resources to auto-close the reader.
- Handle
IOExceptionto catch file errors.
Key Takeaways
Use BufferedReader with FileReader to read files line by line efficiently.
Always check for null from readLine() to avoid errors.
Use try-with-resources to automatically close the file reader.
Handle IOException to manage file reading errors gracefully.
Avoid reading files without buffering for better performance.