Java

Files.readString / readAllLines

admin by @admin ADMIN
6d ago
May 31, 2026
Public
0 0 up · 0 down Sign in to vote
`java.nio.file.Files` shipped these convenience helpers in Java 8/11. Way cleaner than the legacy `FileReader` + `BufferedReader` ceremony for small/medium files.
Java
Raw
import java.io.IOException;
import java.nio.file.*;
import java.nio.charset.StandardCharsets;
import java.util.List;

class Demo {
    void example() throws IOException {
        var path = Path.of("config.toml");

        // Whole file → String (Java 11+)
        String contents = Files.readString(path);
        System.out.println("len = " + contents.length());

        // Whole file → List<String> (one element per line)
        List<String> lines = Files.readAllLines(path);
        for (var line : lines) System.out.println(line);

        // Specify charset explicitly when unsure
        Files.readString(path, StandardCharsets.UTF_8);

        // Stream lines lazily — constant memory, good for big files
        try (var stream = Files.lines(path)) {
            stream.filter(l -> !l.startsWith("#"))
                  .forEach(System.out::println);
        }
    }
}
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.