Reading a plain text file in Java
How can you read a plain text file in Java, and what are the different methods available? Learn what classes like BufferedReader, Scanner, and Files offer for efficiently handling file input in various scenarios.
Reading a plain text file in Java is a common task, and thankfully, there are multiple ways to do it depending on your use case. Java offers built-in classes like BufferedReader, Scanner, and Files (from java.nio) to make file reading efficient and flexible.
Using BufferedReader
One of the most traditional and reliable ways:
BufferedReader reader = new BufferedReader(new FileReader("file.txt"));
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
reader.close();
- Good for reading large files line-by-line.
- Efficient and simple.
Using Scanner
Great for token-based reading or simpler applications:
Scanner scanner = new Scanner(new File("file.txt"));
while (scanner.hasNextLine()) {
System.out.println(scanner.nextLine());
}
scanner.close();
- Very readable and beginner-friendly.
- Offers more control for parsing words or numbers.
Using Files.readAllLines() (Java 8+)
For smaller files where you just need all lines quickly:
List lines = Files.readAllLines(Paths.get("file.txt"));
lines.forEach(System.out::println);
Very concise.
Not suitable for huge files as it loads everything into memory.
Summary:
- Use BufferedReader for line-by-line performance.
- Scanner is easier for simple needs.
- Files.readAllLines() is clean and fast for small files.