Reading files
Read an entire file into a String with one line.
Code Comparison
✕ Java 8
StringBuilder sb = new StringBuilder();
try (BufferedReader br =
new BufferedReader(
new FileReader("data.txt"))) {
String line;
while ((line = br.readLine()) != null)
sb.append(line).append("\n");
}
String content = sb.toString();
✓ Java 11+
String content =
Files.readString(Path.of("data.txt"));
Why the modern way wins
One line
Replace 8 lines of BufferedReader boilerplate.
Auto cleanup
File handle is closed automatically.
UTF-8 default
Correct encoding by default — no charset confusion.
Old Approach
BufferedReader
Modern Approach
Files.readString()
Since JDK
11
Difficulty
beginner
JDK Support
Reading files
Available
Widely available since JDK 11 (Sept 2018)
How it works
Files.readString() reads a file's entire content into a String. It handles encoding (UTF-8 by default) and resource cleanup. For large files, use Files.lines() for lazy streaming.