SyntaxStudy
Sign Up
Java Reading Files with Files and BufferedReader
Java Beginner 1 min read

Reading Files with Files and BufferedReader

Java NIO.2, introduced in Java 7 with the java.nio.file package, provides a modern API for file I/O centred on Path, Files, and Paths. The Files utility class offers high-level convenience methods that handle the boilerplate of opening, reading, and closing streams. Files.readAllLines() reads every line of a text file into a List in a single call — ideal for small to medium files. Files.readString() reads the entire file content as a single String. For large files where loading everything into memory at once is impractical, BufferedReader is the right choice. It wraps an underlying Reader and buffers input, greatly reducing the number of actual I/O calls. You obtain a BufferedReader from Files.newBufferedReader(path, charset), then call readLine() in a loop until it returns null. Using try-with-resources ensures the reader is always closed, even if an exception occurs mid-read. Files.lines() returns a lazily-evaluated Stream of the file's lines, which is a powerful combination with the Stream API: you can filter, map, and collect without loading the entire file. The stream holds an open file handle, so it must be used inside a try-with-resources block to guarantee the handle is released.
Example
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.nio.file.*;
import java.util.List;
import java.util.stream.Collectors;

public class ReadingFilesDemo {

    public static void main(String[] args) throws IOException {
        Path path = Path.of("sample.txt");

        // Create a sample file to read
        Files.writeString(path, "Line 1: Hello\nLine 2: World\nLine 3: Java IO\n");

        // --- Files.readAllLines (loads all into memory) ---
        List<String> lines = Files.readAllLines(path, StandardCharsets.UTF_8);
        System.out.println("readAllLines (" + lines.size() + " lines):");
        lines.forEach(l -> System.out.println("  " + l));

        // --- Files.readString ---
        String content = Files.readString(path, StandardCharsets.UTF_8);
        System.out.println("\nreadString length: " + content.length());

        // --- BufferedReader (good for large files) ---
        System.out.println("\nBufferedReader:");
        try (BufferedReader reader =
                Files.newBufferedReader(path, StandardCharsets.UTF_8)) {
            String line;
            int lineNum = 1;
            while ((line = reader.readLine()) != null) {
                System.out.printf("  %2d: %s%n", lineNum++, line);
            }
        }

        // --- Files.lines() + Stream API ---
        System.out.println("\nFiles.lines() + stream:");
        try (var stream = Files.lines(path, StandardCharsets.UTF_8)) {
            List<String> filtered = stream
                .filter(l -> l.contains("Java"))
                .collect(Collectors.toList());
            System.out.println("Lines containing 'Java': " + filtered);
        }

        Files.deleteIfExists(path); // cleanup
    }
}