All 15 I/O & NIO questions
More in I/O & NIO
Advertisement
Back to results for “Java Fundamentals: Syntax”
Java › I/O & NIO

How do you read all bytes or all lines of a small-to-medium text file in a single, concise call using modern NIO.2 utility methods?

Beginner

Answer

For files small enough to comfortably fit entirely in memory, Files.readString(path) (Java 11+) reads an entire file's content as a single String in one call, and Files.readAllLines(path) reads it as a List<String> (one element per line) -- both dramatically more concise than the older manual approach of opening a BufferedReader and looping with readLine(), appropriate specifically for smaller files where loading everything into memory at once isn't a concern (for very large files, a streaming approach like Files.lines() returning a lazily-evaluated Stream<String> avoids loading the entire file into memory at once).
// Read entire file as one String (Java 11+)
String content = Files.readString(Path.of("config.json"));

// Read entire file as a List of lines
List<String> lines = Files.readAllLines(Path.of("data.csv"));

// For large files: lazily-streamed line-by-line processing instead
try (Stream<String> lineStream = Files.lines(Path.of("huge.log"))) {
    long errorCount = lineStream.filter(line -> line.contains("ERROR")).count();
}
Real-world example A configuration-loading utility reads an entire small JSON config file into a String using the concise Files.readString() one-liner, replacing what would have previously required several lines of manual BufferedReader setup, reading, and closing.

Common follow-ups: At what file size does loading the entire file into memory with readAllLines()/readString() become a genuine concern versus using a streaming approach?;What charset does Files.readString() assume by default, and how would you specify a different one?