Reading a plain text file in Java
Categories:
Reading Plain Text Files in Java: A Comprehensive Guide

Learn various methods to efficiently read plain text files in Java, from basic approaches to modern NIO.2 techniques, handling common challenges like character encodings and resource management.
Reading data from files is a fundamental operation in many Java applications. Whether you're processing configuration files, log data, or large datasets, understanding how to effectively read plain text files is crucial. This article explores several common and efficient ways to read text files in Java, covering both traditional I/O and the more modern NIO.2 API, along with best practices for resource management and error handling.
Traditional Java I/O: FileReader
and BufferedReader
The java.io
package provides foundational classes for input and output operations. For reading text files character by character, FileReader
is often used. However, for improved performance and convenience, BufferedReader
is typically wrapped around a FileReader
. BufferedReader
reads text from a character-input stream, buffering characters to provide for the efficient reading of characters, arrays, and lines.
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class FileReaderExample {
public static void main(String[] args) {
String filePath = "example.txt"; // Ensure this file exists
try (BufferedReader reader = new BufferedReader(new FileReader(filePath))) {
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
System.err.println("Error reading file: " + e.getMessage());
}
}
}
Reading a text file line by line using BufferedReader
and FileReader
.
try-with-resources
statement when dealing with I/O streams. This ensures that the stream is automatically closed, even if exceptions occur, preventing resource leaks.Modern Approach: Java NIO.2 Files
Class
Introduced in Java 7, the NIO.2 API (New I/O) offers significant improvements for file system operations, including more robust and convenient ways to read files. The java.nio.file.Files
class provides static utility methods that simplify common file operations, often reducing boilerplate code. For reading text files, Files.readAllLines()
and Files.lines()
are particularly useful.
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.stream.Stream;
public class Nio2FilesExample {
public static void main(String[] args) {
String filePath = "example.txt";
Path path = Paths.get(filePath);
// Method 1: Read all lines into a List<String>
try {
List<String> allLines = Files.readAllLines(path, StandardCharsets.UTF_8);
System.out.println("\n--- Using Files.readAllLines() ---");
for (String line : allLines) {
System.out.println(line);
}
} catch (IOException e) {
System.err.println("Error reading file with readAllLines: " + e.getMessage());
}
// Method 2: Read lines as a Stream<String> (for large files)
System.out.println("\n--- Using Files.lines() ---");
try (Stream<String> lines = Files.lines(path, StandardCharsets.UTF_8)) {
lines.forEach(System.out::println);
} catch (IOException e) {
System.err.println("Error reading file with lines stream: " + e.getMessage());
}
}
}
Reading a text file using Files.readAllLines()
and Files.lines()
.
Files.readAllLines()
is convenient for smaller files as it loads the entire file content into memory. For very large files, Files.lines()
is more memory-efficient as it returns a Stream<String>
that reads lines lazily.Understanding Character Encodings
A common pitfall when reading text files is incorrect character encoding. If the encoding used to write the file differs from the encoding used to read it, you might encounter garbled characters or MalformedInputException
. Java's FileReader
uses the default platform encoding, which can vary. It's best practice to explicitly specify the character encoding, especially when dealing with international characters or files from different systems.
flowchart TD A[Text File] --> B{Encoding Used to Write?} B -->|UTF-8| C[Read with UTF-8] B -->|ISO-8859-1| D[Read with ISO-8859-1] C --> E[Correct Characters] D --> E B -->|Unknown/Default| F[Read with Platform Default] F --> G{Match?} G -->|Yes| E G -->|No| H[Garbled Characters/Error] style H fill:#f9f,stroke:#333,stroke-width:2px
Flowchart illustrating the importance of matching character encodings when reading text files.
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
public class EncodingExample {
public static void main(String[] args) {
String filePath = "example_utf8.txt"; // Assume this file is UTF-8 encoded
// Explicitly specify UTF-8 encoding
try (BufferedReader reader = new BufferedReader(
new InputStreamReader(new FileInputStream(filePath), StandardCharsets.UTF_8))) {
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
System.err.println("Error reading file with explicit UTF-8: " + e.getMessage());
}
// Example of reading with a potentially incorrect encoding (e.g., ISO-8859-1)
// This might produce incorrect output if the file is truly UTF-8
System.out.println("\n--- Attempting to read with ISO-8859-1 (might be incorrect) ---");
try (BufferedReader reader = new BufferedReader(
new InputStreamReader(new FileInputStream(filePath), StandardCharsets.ISO_8859_1))) {
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
System.err.println("Error reading file with ISO-8859-1: " + e.getMessage());
}
}
}
Specifying character encoding using InputStreamReader
and StandardCharsets
.
FileReader
is simple, it always uses the platform's default character encoding. For robust applications, especially those handling international data, always use InputStreamReader
wrapped around a FileInputStream
and explicitly specify the Charset
(e.g., StandardCharsets.UTF_8
).