Skip to content
KALANBLON
Show contents

Chapter 4 of 6 · 20 min

Reading and writing files with java.nio

By the end of this chapter, you'll be able to

  • Handle paths with Path and read or write a whole file with Files
  • Process a large file line by line with Files.lines and try-with-resources
  • Handle IOException and its specific cases such as NoSuchFileException
  • Write multi-line text with text blocks

Reading and writing in one line

Path represents a file path; the Files class offers the common operations. In the examples, we create temporary files so nothing is left lying around on your machine:

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;

void main() throws IOException {
    Path file = Files.createTempFile("readings", ".csv");
    Files.writeString(file, """
        city;temperature
        Bamako;38.5
        Oslo;-3
        broken line
        Lima;19
        """);

    List<String> lines = Files.readAllLines(file);
    IO.println(lines.size() + " lines read, header: " + lines.getFirst());
    for (String line : lines.subList(1, lines.size())) {
        String[] fields = line.split(";");
        if (fields.length != 2) {
            IO.println("skipped: " + line);
            continue;
        }
        IO.println(fields[0] + " -> " + Double.parseDouble(fields[1]) + " °C");
    }
    Files.delete(file);
    IO.println("still exists? " + Files.exists(file));
}
5 lines read, header: city;temperature
Bamako -> 38.5 °C
Oslo -> -3.0 °C
skipped: broken line
Lima -> 19.0 °C
still exists? false
  • """…""" is a text block: multi-line text, without writing \n. The indentation shared by all lines is removed automatically.
  • Files.writeString and Files.readString write and read the whole file, in UTF-8 by default. Files.readAllLines returns a list of lines, without the line breaks.
  • main declares throws IOException: file operations can throw this checked exception, and the compiler requires you to handle or declare it.
  • getFirst() (Java 21+) returns the first element of a list; subList(1, n) a view of the following elements.

Large files: line by line

readAllLines loads everything into memory: fine for a small file, impossible for a log of several gigabytes. Files.lines returns a lazy stream that reads as it goes. It keeps the file open: put it in a try-with-resources, which closes it automatically.

import java.io.BufferedWriter;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.stream.Stream;

void main() throws IOException {
    Path log = Files.createTempFile("log", ".log");
    try (BufferedWriter out = Files.newBufferedWriter(log)) {
        for (int i = 1; i <= 5; i++) {
            out.write("visit " + i + (i % 2 == 0 ? " mobile" : " desktop"));
            out.newLine();
        }
    }
    try (Stream<String> lines = Files.lines(log)) {
        long mobile = lines.filter(l -> l.endsWith("mobile")).count();
        IO.println(mobile + " visits on mobile");
    }
    Files.delete(log);
}
2 visits on mobile

try (Resource r = …) { … } automatically calls r.close() at the end of the block, even if an exception occurs. It's Java's equivalent of RAII or Python's with.

…the file is closed before the exception travels up. No leak.

Step 5 of 5
Text description of the animation
  1. The file is opened; the stream will read the lines as it goes.
  2. Lines go by one at a time: never the whole file in memory.
  3. At the end of the block, Java closes the stream, and so the file.
  4. If reading fails halfway…
  5. …the file is closed before the exception travels up. No leak.

Handling file errors

IOException has specific subclasses: NoSuchFileException (missing file), AccessDeniedException (insufficient permissions)… Catch what you know how to handle, and let the rest travel up:

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.NoSuchFileException;
import java.nio.file.Path;

String readConfiguration(Path path) {
    try {
        return Files.readString(path).strip();
    } catch (NoSuchFileException e) {
        return "default values";
    } catch (IOException e) {
        throw new UncheckedIOException("cannot read: " + path, e);
    }
}

void main() throws IOException {
    Path missing = Path.of("missing-configuration.txt");
    IO.println(readConfiguration(missing));
    Path present = Files.createTempFile("config", ".txt");
    Files.writeString(present, "theme=dark\n");
    IO.println(readConfiguration(present));
    Files.delete(present);
}
default values
theme=dark

A missing configuration file is a normal case: we use default values. Any other error is wrapped in an UncheckedIOException, keeping the original exception as the cause (the second argument), which is invaluable for diagnosis.

Your turn

Worked exercise

Solved exercise: text statistics

Write a method Stats analyse(Path file) throws IOException that returns a record Stats(int lines, int words, String longest): the number of lines, the number of words, and the longest word (in case of a tie, the first in alphabetical order). Test it on a temporary file containing three lines of text and one empty line.

Hint 1
Files.readAllLines(file) gives the lines. l.split("\\s+") splits a line on spaces, and flatMap(l -> Arrays.stream(...)) puts all the words of all the lines into a single stream.
Hint 2
An empty line produces an empty "word": filter with !w.isBlank(). For the longest: Comparator.comparingInt(String::length).thenComparing(Comparator.reverseOrder()): on equal length, max then keeps the first word in alphabetical order.
Show the solution and common mistakes
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;

record Stats(int lines, int words, String longest) {}

Stats analyse(Path file) throws IOException {
    List<String> lines = Files.readAllLines(file);
    List<String> words = lines.stream()
        .flatMap(l -> Arrays.stream(l.split("\\s+")))
        .filter(w -> !w.isBlank())
        .toList();
    String longest = words.stream().max(Comparator.comparingInt(String::length).thenComparing(Comparator.reverseOrder())).orElse("");
    return new Stats(lines.size(), words.size(), longest);
}

void main() throws IOException {
    Path f = Files.createTempFile("text", ".txt");
    Files.writeString(f, "The baobab stores water\nthroughout the dry season\n\nit can live a thousand years\n");
    IO.println(analyse(f));
    Files.delete(f);
}
Stats[lines=4, words=14, longest=throughout]

Watch the tie-break: max keeps the greatest element according to the comparator. With naturalOrder() as the second criterion, on equal length it would keep the last word in alphabetical order; reverseOrder() flips that criterion to keep the first one.

Common mistakes:

  • Forgetting the isBlank() filter: the empty line adds an empty word, and the count goes up to 15.
  • Using Files.lines without try-with-resources: the file stays open until the garbage collector deals with it, which can block its deletion, especially on Windows.

Summary

  1. 1Path designates a file; Files reads and writes it in one line (readString, writeString, readAllLines).
  2. 2Files.lines reads a large file line by line; put it in a try-with-resources.
  3. 3try-with-resources closes the resource automatically, even when an exception occurs.
  4. 4IOException is checked: handle it or declare it with throws, never an empty catch.
  5. 5Text blocks ("""…""") write multi-line text without \n.

Your progress is saved on this device. Create a free account to keep your progress on all your devices.