← All lessons
Advanced Java · Lesson 4 of 9

Files and resources

Programs that only use memory forget everything when they stop. Files let data outlive the program. Modern Java works with files through java.nio.file: a Path names a file or folder, and the Files class has static methods to read, write, copy, move and list them. Reading a file can fail (it might not exist), so these methods throw the checked IOException.

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

public class Main {
    public static void main(String[] args) throws IOException {
        Path file = Files.createTempFile("notes", ".txt");
        Files.writeString(file, "milk\neggs\nbread\n");
        Files.writeString(file, "jam\n", StandardOpenOption.APPEND);

        List<String> lines = Files.readAllLines(file);
        System.out.println(lines.size() + " lines, last is " + lines.get(lines.size() - 1));
        System.out.println(Files.exists(file) + " " + Files.size(file) + " bytes");
        System.out.println(file.getFileName().toString().endsWith(".txt"));
        Files.delete(file);
        System.out.println(Files.exists(file));
    }
}
Prints
4 lines, last is jam
true 20 bytes
true
false

A real program would use a fixed path like Path.of("data", "notes.txt") (relative to where the program was started) instead of a temporary file. Path.of joins the parts with the right separator for the system, / or \. Files.readString reads the whole file as one string; readAllLines splits it into lines.

Big files, and try-with-resources

readAllLines loads the whole file into memory, which is fine for small files and a disaster for a 20 GB log. Files.lines gives a stream that reads lazily, one line at a time. Anything that holds a file open is a resource and must be closed afterwards, or the program leaks file handles until the system refuses to open more. try-with-resources closes it for you, even when an exception is thrown:

Java
import java.io.*;
import java.nio.file.*;
import java.util.stream.*;

public class Main {
    public static void main(String[] args) throws IOException {
        Path log = Files.createTempFile("app", ".log");
        Files.write(log, java.util.List.of("INFO start", "WARN slow disk", "ERROR db down", "INFO retry", "ERROR db down"));

        try (Stream<String> lines = Files.lines(log)) {
            long errors = lines.filter(l -> l.startsWith("ERROR")).count();
            System.out.println(errors + " errors");
        }

        try (BufferedReader in = Files.newBufferedReader(log)) {
            String line;
            int n = 0;
            while ((line = in.readLine()) != null) {
                n++;
                if (line.startsWith("WARN")) System.out.println("line " + n + ": " + line);
            }
        }
        Files.delete(log);
    }
}
Prints
2 errors
line 2: WARN slow disk

Whatever is made in the brackets after try is closed when the block ends, in reverse order if there are several. It works for any class that implements AutoCloseable: files, network connections, database connections.

Encodings

A file holds bytes, not letters. An encoding says how letters become bytes. UTF-8 is the standard today and covers every language; é takes two bytes in it, a Thai letter three. The Files methods use UTF-8 unless told otherwise. Reading a file with the wrong encoding garbles accented letters into things like é, so when a file comes from elsewhere, find out its encoding and pass it: Files.readString(p, StandardCharsets.ISO_8859_1).

Java
String word = "café";
System.out.println(word.length());
System.out.println(word.getBytes(java.nio.charset.StandardCharsets.UTF_8).length);
Prints
4
5

Parsing a CSV line by line

Reading data files means expecting bad lines. Parse each line on its own, skip or report the bad ones with their line number, and keep going:

Java
List<String> csv = List.of("name,qty,price", "pens,10,1.25", "ink,two,4.00", "paper,5", "tape,3,2.50");
double total = 0;
for (int i = 1; i < csv.size(); i++) {
    String[] f = csv.get(i).split(",", -1);
    try {
        if (f.length != 3) throw new IllegalArgumentException("expected 3 fields, got " + f.length);
        total += Integer.parseInt(f[1]) * Double.parseDouble(f[2]);
    } catch (IllegalArgumentException e) {
        System.out.println("line " + (i + 1) + " skipped: " + e.getMessage());
    }
}
System.out.printf("total %.2f%n", total);
Prints
line 3 skipped: For input string: "two"
line 4 skipped: expected 3 fields, got 2
total 20.00

NumberFormatException is a kind of IllegalArgumentException, so one catch covers both problems. Real CSV has quoted fields with commas inside ("Smith, Ana"), which a plain split gets wrong; for real data, use a CSV library.

Name the file and the line number in every error about a data file. "bad number" sends someone hunting; "orders.csv line 5004: qty 'two' isn't a number" gets fixed in a minute.

Practice

Why use try-with-resources when reading a file?

More info

Quick reference

Path.of("a", "b.txt")A file path, joined with the system's separator.
Files.readString / readAllLinesWhole file as text / as a list of lines.
Files.writeString / writeWrite text / lines (APPEND to add).
Files.lines(p)A lazy stream of lines; close it with try-with-resources.
try (Res r = ...) { }try-with-resources: r is closed when the block ends.
IOExceptionChecked: file and network operations can fail.
UTF-8The standard encoding; é is 2 bytes.
split(",", -1)Keep empty trailing fields.

Related courses