GeezerVisonThe World Wide Web, restored to 800 pixels of glory. |
| Home|About|Gaming cabinet|Archives|How it works|Starter sites |
GeezerVison is showing javaevolved.dev โ Reading files | java.evolved
I/O
Beginner
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"));
See a problem with this code? Let us know.
Why the modern way wins
๐
One lineReplace 8 lines of BufferedReader boilerplate. ๐งน
Auto cleanupFile handle is closed automatically. ๐
UTF-8 defaultCorrect 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. Related Documentation
Proof
Related patterns
I/O
Beginner
Try-with-resources improvementJava 8
Connection conn = getConnection();
// Must re-declare in try
try (Connection c = conn) {
use(c);
}
Java 9+
Connection conn = getConnection();
// Use existing variable directly
try (conn) {
use(conn);
}
JDK 9+
โ
I/O
Beginner
Writing filesJava 8
try (FileWriter fw =
new FileWriter("out.txt");
BufferedWriter bw =
new BufferedWriter(fw)) {
bw.write(content);
}
Java 11+
Files.writeString(
Path.of("out.txt"),
content
);
JDK 11+
โ
I/O
Beginner
Files.mismatch()Java 8
// Compare two files byte by byte byte[] f1 = Files.readAllBytes(path1); byte[] f2 = Files.readAllBytes(path2); boolean equal = Arrays.equals(f1, f2); // loads both files entirely into memory Java 12+
long pos = Files.mismatch(path1, path2); // -1 if identical // otherwise: position of first difference
JDK 12+
โ
|
| You are visitor 01402503 โ GeezerVison does not store the pages you look up. Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800ร600. No cookies required. |