In this Java tutorial, you will learn how to read contents of a File line by line using BufferedReader class, with examples.
The usual pattern is simple: create a BufferedReader, call readLine() inside a loop, and stop when readLine() returns null. This reads one line at a time instead of loading the whole text file into memory.
Read contents of a file line by line using BufferedReader
Following are the steps to read contents of a File line by line using BufferedReader:
Step 1: Load the file into buffer of BufferedReader.
BufferedReader br = new BufferedReader(new FileReader(filename));
BufferedReader provides an efficient way of reading characters, lines and arrays, from a character stream.
Step 2: Use java.io.BufferedReader.readLine() method to get a line and iterative calls to the method brings us the subsequent lines.
line = br.readLine();
If stream from the specified file contains characters, readLine() returns characters till the encounter of new line or line feed. And if the stream is empty, i.e., no more characters left in the stream, the method returns null, which is an indication that whole contents of file have been read.
How BufferedReader readLine() works in Java file reading
The readLine() method reads a line of text and returns it as a String. The returned string does not include the line separator characters such as \n or \r\n. When the end of the file is reached, readLine() returns null.
A common loop for reading a text file line by line is shown below.
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
The assignment line = br.readLine() reads the next line. The comparison != null checks whether there is still a line to process. This pattern is widely used for text files, logs, CSV-like files, and configuration files when each line can be processed independently.
Examples
1. Read File Line by Line using BufferedReader
In this example, we have a text file named samplefile.txt, and we will read contents of this file, line by line, using BufferedReader class.
samplefile.txt
This is first line.
This is second line.
This is third line.
Welcome to www.tutorialkart.com.
Example.java
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
/**
* Read contents of a File line by line using BufferedReader
* www.tutorialkart.com
*/
public class Example {
public static void main(String args[]){
String filename = "samplefile.txt";
BufferedReader br = null;
String line = "";
try {
br = new BufferedReader(new FileReader(filename));
System.out.println("---------Contents of the file---------\n-------------------------------------\n");
while( (line = br.readLine()) != null){
System.out.println(line);
}
} catch (FileNotFoundException e) {
System.err.println("Oops! Please check for the presence of file in the path specified.");
e.printStackTrace();
} catch (IOException e) {
System.err.println("Oops! Unable to read the file.");
e.printStackTrace();
}
}
}
When the above program is run, output to the console is as shown in the following.
Output
---------Contents of the file---------
-------------------------------------
This is first line.
This is second line.
This is third line.
Welcome to www.tutorialkart.com.
Note : Provide the path to the file correctly. In this example, the file is placed at the root of Project Folder (of Eclipse Project).
Read a Java text file line by line with try-with-resources
In modern Java code, prefer try-with-resources when using BufferedReader. It closes the reader automatically, even if an exception occurs while reading the file.
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class Example {
public static void main(String[] args) {
String filename = "samplefile.txt";
try (BufferedReader br = new BufferedReader(new FileReader(filename))) {
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
System.err.println("Unable to read the file: " + e.getMessage());
}
}
}
This version is shorter and safer because there is no need to close br manually in a finally block.
Read a UTF-8 file line by line using BufferedReader in Java
FileReader uses the default character encoding of the Java runtime. If your file has a known encoding such as UTF-8, use Files.newBufferedReader() with StandardCharsets.UTF_8. This avoids wrong characters when the file contains symbols, accents, or non-English text.
import java.io.BufferedReader;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
public class Example {
public static void main(String[] args) {
Path path = Path.of("samplefile.txt");
try (BufferedReader br = Files.newBufferedReader(path, StandardCharsets.UTF_8)) {
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
System.err.println("Unable to read the file: " + e.getMessage());
}
}
}
Use this approach when the file encoding matters. For many application files and data exports, UTF-8 is the expected encoding.
Read a large file line by line using BufferedReader
BufferedReader is suitable for large text files because the program processes one line at a time. It does not create a list containing all lines unless you explicitly store them.
long lineCount = 0;
try (BufferedReader br = new BufferedReader(new FileReader("large-file.txt"))) {
while (br.readLine() != null) {
lineCount++;
}
}
System.out.println("Total lines: " + lineCount);
For very large files, avoid adding every line to an ArrayList unless you really need all lines in memory. Also note that a single extremely long line can still require significant memory because that full line must be represented as a String.
BufferedReader vs Files.lines for reading lines in Java
Java also provides Files.lines(), which returns a stream of lines. It is useful when you want to use stream operations such as filter(), map(), or count(). The stream must be closed, so use it inside try-with-resources.
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.stream.Stream;
public class Example {
public static void main(String[] args) {
Path path = Path.of("samplefile.txt");
try (Stream<String> lines = Files.lines(path)) {
lines.forEach(System.out::println);
} catch (IOException e) {
System.err.println("Unable to read the file: " + e.getMessage());
}
}
}
Use BufferedReader when you want a clear loop and simple exception handling. Use Files.lines() when stream processing makes the code easier to read.
Common mistakes when using BufferedReader to read a file line by line
- Not closing the reader: Use
try-with-resourcesso the file handle is released automatically. - Using the wrong file path: If only a filename is given, Java looks in the current working directory of the program.
- Expecting line separators in the returned string:
readLine()removes the line-ending characters. - Ignoring character encoding: Use
Files.newBufferedReader(path, StandardCharsets.UTF_8)when the encoding is known. - Storing all lines unnecessarily: For large files, process each line inside the loop instead of collecting every line in memory.
QA checklist for this Java BufferedReader file reading tutorial
- Does the tutorial show the correct
while ((line = br.readLine()) != null)pattern? - Does every new Java code block use a PrismJS-compatible
language-javaclass? - Does the explanation mention that
readLine()returnsnullat the end of the file? - Does the improved example close the
BufferedReaderwithtry-with-resources? - Does the tutorial warn about file paths and character encoding where they affect Java file reading?
FAQs on reading a file line by line using BufferedReader in Java
How to read a file line by line in Java using BufferedReader?
Create a BufferedReader for the file and call readLine() inside a loop. Continue until readLine() returns null.
try (BufferedReader br = new BufferedReader(new FileReader("samplefile.txt"))) {
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
}
What does BufferedReader readLine() return at the end of a file?
At the end of the file, readLine() returns null. This is why the condition while ((line = br.readLine()) != null) is used when reading a file line by line.
Does BufferedReader readLine() include the newline character?
No. readLine() returns the text of the line without the line separator. If you print each line using System.out.println(), Java adds a new line while printing.
Can BufferedReader read a huge file in Java?
Yes, BufferedReader can be used for large text files because it reads and processes one line at a time. However, avoid storing all lines in a collection if the file is very large.
Should I use BufferedReader or Files.lines in Java?
Use BufferedReader for a simple, explicit loop. Use Files.lines() when you want to process the file as a stream. In both cases, close the resource with try-with-resources.
Conclusion
In this Java Tutorial, we have seen how to use java.io.BufferedReader and its methodjava.io.BufferedReader.readLine() to read the contents of a file line by line.
TutorialKart.com