-
Notifications
You must be signed in to change notification settings - Fork 24
Expand file tree
/
Copy pathreading-files.yaml
More file actions
52 lines (52 loc) · 1.68 KB
/
reading-files.yaml
File metadata and controls
52 lines (52 loc) · 1.68 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
---
id: 57
slug: "reading-files"
title: "Reading files"
category: "io"
difficulty: "beginner"
jdkVersion: "11"
oldLabel: "Java 8"
modernLabel: "Java 11+"
oldApproach: "BufferedReader"
modernApproach: "Files.readString()"
oldCode: |-
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();
modernCode: |-
String content =
Files.readString(Path.of("data.txt"));
summary: "Read an entire file into a String with one line."
explanation: "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."
whyModernWins:
- icon: "📏"
title: "One line"
desc: "Replace 8 lines of BufferedReader boilerplate."
- icon: "🧹"
title: "Auto cleanup"
desc: "File handle is closed automatically."
- icon: "🌐"
title: "UTF-8 default"
desc: "Correct encoding by default — no charset confusion."
support:
state: "available"
description: "Widely available since JDK 11 (Sept 2018)"
prev: "io/io-class-console-io"
next: "io/writing-files"
related:
- "io/try-with-resources-effectively-final"
- "io/writing-files"
- "io/files-mismatch"
docs:
- title: "Files.readString()"
href: "https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/nio/file/Files.html#readString(java.nio.file.Path)"
- title: "Files.readAllLines()"
href: "https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/nio/file/Files.html#readAllLines(java.nio.file.Path)"