Java Read Files β Efficient File Reading in Java
Introduction β Why File Reading Matters
Reading data from files is a critical part of many Java applicationsβwhether it’s loading configuration settings, importing datasets, or reading logs. Java provides a variety of APIs to read files, from traditional methods like FileReader to modern approaches like Files.readAllLines().
In this guide, you’ll learn:
- How to read files in Java using different techniques
- When to use
FileReader,BufferedReader,Scanner, orFiles - How to handle exceptions and resources safely
- Performance tips and best practices for large file reading
Java File Reading Classes
| Class/Method | Use Case |
|---|---|
FileReader | Basic character stream reading |
BufferedReader | Efficient reading of text, line by line |
Scanner | Token-based reading (great for parsing) |
Files.readAllLines() | Simple and modern, reads all lines into a list |
Files.lines() | Lazy stream-based reading |
Read File Using FileReader
import java.io.FileReader;
import java.io.IOException;
public class FileReaderExample {
public static void main(String[] args) {
try (FileReader reader = new FileReader("example.txt")) {
int character;
while ((character = reader.read()) != -1) {
System.out.print((char) character);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
Explanation:
- Reads character-by-character
- Suitable for small text files
- Uses try-with-resources to auto-close
Read File Using BufferedReader
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class BufferedReaderExample {
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) {
e.printStackTrace();
}
}
}
Explanation:
- Efficient for line-by-line reading
- Avoids character-by-character I/O bottlenecks
- Ideal for reading logs or text files line-by-line
Read File Using Scanner
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class ScannerExample {
public static void main(String[] args) {
try (Scanner scanner = new Scanner(new File("example.txt"))) {
while (scanner.hasNextLine()) {
System.out.println(scanner.nextLine());
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
Explanation:
- Great for parsing numbers, words, tokens
- Use
.hasNext(),.nextInt(),.nextDouble()etc. - More flexible for structured file content
Read All Lines Using Files.readAllLines()
import java.nio.file.*;
import java.io.IOException;
import java.util.List;
public class FilesReadAllLinesExample {
public static void main(String[] args) throws IOException {
List<String> lines = Files.readAllLines(Paths.get("example.txt"));
lines.forEach(System.out::println);
}
}
Explanation:
- Reads all lines into a
List<String> - Simple and modern, but loads entire file into memory
- Suitable for small to medium files
Stream-based Reading Using Files.lines()
Files.lines(Paths.get("example.txt"))
.filter(line -> !line.isEmpty())
.forEach(System.out::println);
Explanation:
- Returns a Stream of lines for efficient, lazy processing
- Can filter, map, reduce during reading
Tip: Always close streams or use try-with-resources.
Comparison Table
| Method | Best For | Memory Usage | Buffered? | Java Version |
|---|---|---|---|---|
FileReader | Small files, character reading | Low | 1.0+ | |
BufferedReader | Line-by-line reading | Low | 1.1+ | |
Scanner | Token parsing | Medium | 1.5+ | |
Files.readAllLines() | Small to mid files | High | 1.7+ | |
Files.lines() | Large files, streaming processing | Low (streamed) | 1.8+ |
Best Practices
- Use
BufferedReaderorFiles.lines()for large files - Always use
try-with-resourcesto auto-close readers - Avoid
readAllLines()on large files β memory overload - Prefer
FilesAPI for modern Java apps - Handle
IOExceptionandFileNotFoundExceptionproperly
Summary β Java File Reading Techniques
Java offers flexible file reading methods for different scenarios β whether you need line-by-line efficiency, token-based parsing, or modern stream processing.
Key Takeaways:
- Use
FileReaderandBufferedReaderfor traditional reading - Use
Scannerfor parsing structured text - Use
Files.readAllLines()for simplicity (small files) - Use
Files.lines()for memory-efficient streaming - Apply
try-with-resourcesand exception handling always
FAQs β Java Read Files
What is the easiest way to read a file in Java?
Use Files.readAllLines() for small files or Files.lines() for large files with stream processing.
How to read a file line-by-line in Java?
Use BufferedReader.readLine() inside a loop or Scanner.nextLine().
Which is better: BufferedReader or Scanner?
Use BufferedReader for performance, and Scanner for parsing tokens like integers or words.
How to avoid memory issues with large files?
Use Files.lines() or BufferedReader, which read line-by-line instead of loading entire content at once.
Can I read files with UTF-8 encoding?
Yes, use new InputStreamReader(new FileInputStream("file.txt"), StandardCharsets.UTF_8) or specify charset in Files.newBufferedReader().
Share Now :
