IntermediateLesson 13 of 205 min read

Files and Text: Reading and Writing With java.nio

Learn to write and read text files with Files and Path, process lines, handle missing files and use a temporary directory, with real files created and checked by a second program.

In this lesson you will

  • Use Path and Files
  • Write, append and read lines
  • Handle missing files
  • Parse a small data file

About 28 minutes

Bookings that survive a restart

Until now Hana’s bookings lived in memory and vanished when the program ended. Saving them to a file is the first step toward a real application. Modern Java reads and writes files with two classes in java.nio.file: Path, which names a location, and Files, which does the work. Their methods throw IOException, a checked exception, so the compiler makes sure that you have decided what happens when a disk or a path misbehaves.

Need Method
Name a file Path.of(“dir”, “bookings.csv”)
Write text Files.writeString(path, text)
Write lines Files.write(path, lines)
Append Files.writeString(path, text, StandardOpenOption.APPEND)
Read everything Files.readString(path) or Files.readAllLines(path)
Check Files.exists, Files.size
Temporary directory Files.createTempDirectory(“name”)

Text files need an encoding. The methods above use UTF-8 by default since Java 18, which is the right choice almost everywhere. For very large files, Files.lines(path) reads lazily as a stream instead of loading everything, and it should be closed, ideally with try-with-resources. A simple data format is CSV, values separated by commas, which you can split with String.split. Real CSV files can contain quoted commas, and for those you would use a proper parsing library.

import java.io.IOException;
import java.nio.file.*;
import java.util.*;

public class Main {
    public static void main(String[] args) throws IOException {
        Path dir = Files.createTempDirectory("bikes");
        Path file = dir.resolve("bookings.csv");
        Files.write(file, List.of("bike,days,weekend", "City 1,3,0", "Trail 2,4,2"));
        Files.writeString(file, "Tandem 3,7,3\n", StandardOpenOption.APPEND);
        System.out.println("exists: " + Files.exists(file) + ", size: " + Files.size(file) + " bytes");
        List<String> lines = Files.readAllLines(file);
        System.out.println("lines: " + lines.size() + ", header: " + lines.get(0));
        int days = 0, weekend = 0;
        for (String line : lines.subList(1, lines.size())) {
            String[] p = line.split(",");
            days += Integer.parseInt(p[1].trim());
            weekend += Integer.parseInt(p[2].trim());
            System.out.println("  " + p[0] + ": " + p[1] + " days, " + p[2] + " on weekends");
        }
        System.out.println("total days " + days + ", weekend days " + weekend);
        try {
            Files.readString(dir.resolve("missing.csv"));
        } catch (NoSuchFileException e) {
            System.out.println("NoSuchFileException for " + e.getFile().substring(e.getFile().lastIndexOf('/') + 1));
        }
        try (var stream = Files.lines(file)) {
            System.out.println("lines containing 'Trail': " + stream.filter(s -> s.contains("Trail")).count());
        }
        Files.delete(file); Files.delete(dir);
        System.out.println("cleaned up, directory exists: " + Files.exists(dir));
    }
}
exists: true, size: 54 bytes
lines: 4, header: bike,days,weekend
  City 1: 3 days, 0 on weekends
  Trail 2: 4 days, 2 on weekends
  Tandem 3: 7 days, 3 on weekends
total days 14, weekend days 5
NoSuchFileException for missing.csv
lines containing 'Trail': 1
cleaned up, directory exists: false

The file was created in a temporary directory, and Java reported 54 bytes. We can check that against the text: the header and three rows add up to 54 characters including the line breaks, and since all characters are plain ASCII, each is one byte. Reading the file back gave 4 lines, which is the header and three bookings. Parsing the rows, the program found 14 rental days in total, 5 of them on weekends.

The missing file produced a NoSuchFileException, a subclass of IOException that you can catch separately to tell “the file is not there” from “the disk failed”. The lazy stream version counted the one line that contains “Trail”, and the try-with-resources closed the stream afterwards. At the end the program deleted the file and the directory, and confirmed that the directory was gone. Temporary directories are the right place for experiments and for tests, since nothing is left behind.

Check by hand: the header “bike,days,weekend” is 17 characters plus a line break, “City 1,3,0” is 10 plus 1, “Trail 2,4,2” is 11 plus 1 and “Tandem 3,7,3” is 12 plus 1, which gives 18 + 11 + 12 + 13 = 54 bytes. The days are 3 + 4 + 7 = 14 and the weekend days 0 + 2 + 3 = 5.

Encoding and line endings

Two details cause surprises when files move between computers. The first is the encoding: if a file is written in one encoding and read in another, accented letters turn into question marks or odd symbols, so it is wise to name UTF-8 explicitly when you can, for example with StandardCharsets.UTF_8, and to agree on it with whoever else uses the file. The second is the line ending: Windows traditionally uses two characters and Linux and macOS one, and the readAllLines method hides the difference by treating both as a line break, while manual splitting on a single character does not.

Close what you open

Streams from Files.lines and similar methods hold the file open. Use try-with-resources so that they are closed even when an exception happens.

Keep paths out of your code logic

Build paths with Path.of and resolve, never by joining strings with slashes, so that the code works on Windows, macOS and Linux alike.

About this course

Every program in this lesson was compiled and run with OpenJDK 21 while the course was written. Java releases twice a year, so check the official Java documentation for the current version and for features added after Java 21.

Practice

Write a program that reads the bookings file and prints the booking with the most days. Then extend it to write a summary file with one line per bike and the total price, using the rules from the invoice project. Try it with a file that has a blank line at the end and see what your parsing does.

Check what you learned

Five quick questions. Pick an answer and you will see straight away whether it is right and why.

Which class names a location on disk?

  1. Files
  2. Path
  3. String only
  4. Scanner

Files does the work with it.

What does Files.readAllLines return?

  1. A list of lines
  2. A single byte
  3. A number
  4. An array of chars

It loads the whole file.

Which exception means the file is missing?

  1. NoSuchFileException
  2. ArithmeticException
  3. NullPointerException
  4. ClassCastException

It is a kind of IOException.

Why use try-with-resources with Files.lines?

  1. It makes it faster
  2. It encrypts it
  3. It sorts lines
  4. It closes the file automatically

The stream holds the file open.

What is the safest way to build a path?

  1. Joining strings with slashes
  2. Typing the full text each time
  3. Using a number
  4. Path.of and resolve

It is portable.

Summary

  • Path names a location and Files reads and writes it.
  • IOException is checked, so handle it deliberately.
  • Close lazy streams with try-with-resources.
  • Verify sizes and totals by hand.

Next lesson

Lesson 14 introduces lambdas and streams.

Questions

How do I read a very large file?

Use Files.lines or a BufferedReader to process one line at a time instead of loading everything.

What about binary files?

Files.readAllBytes and Files.write with a byte array, or streams, handle binary data.

Is CSV parsing with split enough?

For simple data, yes. Quoted fields and embedded commas need a CSV library.

Progress is saved in this browser.