GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • java.evolved
  • โ†
  • โ†’

This view

  • Original page
  • New address

GeezerVison is showing javaevolved.dev โ€” Reading files | java.evolved

Home / I/O / Reading files
I/O Beginner

Reading files

  • ๐Ÿ› Report a code issue
  • ๐ŸŒ Report a translation issue
  • ๐Ÿ’ก Suggest a new pattern

Read an entire file into a String with one line.

I/O
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"));
Share ๐•
See a problem with this code? Let us know.
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.

Related Documentation
Files.readString() โ†— Files.readAllLines() โ†—
Proof
View proof source โ†—
Related patterns
I/O Beginner

Try-with-resources improvement

Java 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);
}
Hover to see modern โžœ
JDK 9+ โ†’
I/O Beginner

Writing files

Java 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
);
Hover to see modern โžœ
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
Hover to see modern โžœ
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.