javabeginner

Read File Line by Line in Java

Read files using BufferedReader, Files.readAllLines, and Stream API with proper resource management.

java
import java.io.*;
import java.nio.file.*;
import java.util.List;
import java.util.stream.Stream;

public class FileReader {
    // 1. Files.readAllLines — small files
    public static List<String> readAll(String path) throws IOException {
        return Files.readAllLines(Path.of(path));
    }

    // 2. BufferedReader — large files, line by line
    public static void readBuffered(String path) throws IOException {
        try (var reader = new BufferedReader(new java.io.FileReader(path))) {
            String line;
            while ((line = reader.readLine()) != null) {
                System.out.println(line);
            }
        }
    }

    // 3. Stream — lazy, memory-efficient
    public static void readStream(String path) throws IOException {
        try (Stream<String> lines = Files.lines(Path.of(path))) {
            lines.filter(l -> !l.isBlank())
                 .map(String::trim)
                 .forEach(System.out::println);
        }
    }

    public static void main(String[] args) throws IOException {
        List<String> all = readAll("data.txt");
        System.out.println("Lines: " + all.size());
    }
}

Use Cases

  • Processing log files line by line
  • Reading configuration files
  • Memory-efficient large file processing

Tags

Related Snippets

Similar patterns you can reuse in the same workflow.