← 返回课程: Java from scratch

Reading and writing files with NIO

视频即将上线

A program that forgets everything when it closes has limited use. To keep data between runs, read settings or process records you need to work with files. Modern Java offers the NIO.2 API, in the java.nio.file package, with two main classes: Path, which represents a path, and Files, which holds static methods to read, write, copy and delete. It is much more comfortable than the old File with manual streams, and it combines very well with what you already know: exceptions, try-with-resources and streams.

Path and Files

A path is created with Path.of("data", "notes.txt"), which uses the right separator on each operating system. Files.writeString and Files.readString work with a whole file as text; Files.readAllLines returns a list with one line per element; Files.write with a list of lines writes several. By default, writing overwrites the file; to append at the end use StandardOpenOption.APPEND (together with CREATE if it may not exist). All these methods throw IOException, a checked exception, so you must catch it or declare it with throws. Always use UTF-8, which is the default in these methods, so as not to damage accents.

java
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardOpenOption;
import java.util.List;

public class Main {
    public static void main(String[] args) {
        try {
            Path dir = Files.createTempDirectory("javademo");   // safe scratch folder
            Path file = dir.resolve("notes.txt");

            Files.writeString(file, "first line\nsecond line\n");
            Files.writeString(file, "third line\n", StandardOpenOption.APPEND);

            System.out.println(Files.exists(file));            // true
            System.out.println(Files.size(file) > 0);          // true

            List<String> lines = Files.readAllLines(file);
            System.out.println(lines.size());                  // 3
            for (String line : lines) {
                System.out.println("> " + line);
            }

            String all = Files.readString(file);
            System.out.println(all.length());                  // 34

            Files.delete(file);
            Files.delete(dir);
            System.out.println(Files.exists(file));            // false
        } catch (IOException e) {
            System.out.println("I/O error: " + e.getMessage());
        }

        try {
            Files.readString(Path.of("does-not-exist.txt"));
        } catch (IOException e) {
            System.out.println("Missing file: " + e.getClass().getSimpleName());
        }
    }
}

Processing big files and CSV

Files.readAllLines loads everything into memory, which is unsuitable for a file of several gigabytes. For those cases Files.lines returns a Stream<String> that reads line by line; since it keeps the file open, it must be used inside a try-with-resources. A very common format is CSV: comma-separated values, one row per line. With split(",") and a record you can turn each line into an object and process the set with the streams from the previous lesson. Remember to validate: a malformed line must not break the program, but be logged and skipped.

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

public class Main {
    record Sale(String product, int units, double price) {
        double total() { return units * price; }
    }

    static Sale parse(String line) {
        String[] parts = line.split(",");
        if (parts.length != 3) throw new IllegalArgumentException("bad line: " + line);
        return new Sale(parts[0].trim(), Integer.parseInt(parts[1].trim()),
                        Double.parseDouble(parts[2].trim()));
    }

    public static void main(String[] args) throws IOException {
        Path file = Files.createTempFile("sales", ".csv");
        Files.write(file, List.of("pen,10,1.5", "book,2,12.0", "oops", "lamp,x,30"));

        List<Sale> sales = new ArrayList<>();
        try (Stream<String> lines = Files.lines(file)) {      // closed automatically
            for (String line : (Iterable<String>) lines::iterator) {
                try {
                    sales.add(parse(line));
                } catch (IllegalArgumentException e) {         // NumberFormatException too
                    System.out.println("Skipped: " + line);
                }
            }
        }

        double total = sales.stream().mapToDouble(Sale::total).sum();
        System.out.println(sales.size() + " valid sales, total " + total);  // 2 valid, 39.0
        Files.delete(file);
    }
}
  • NoSuchFileException (subclass of IOException): the file or folder does not exist; check the path and the working directory.
  • FileAlreadyExistsException: you try to create something that already exists; use createDirectories, which does not complain if it exists.
  • Relative paths: they are resolved from the folder where you run java, not from where the source code is.
  • Forgetting APPEND: every writeString overwrites the previous content.
  • Using Files.readAllLines on a huge file: it can exhaust memory; use Files.lines.
  • Leaving a Files.lines Stream unclosed: it keeps the file locked, especially on Windows.

✎ 我的笔记

仅保存在此浏览器中。登录后可保存到账号。0/5000 字符

← 上一节下一节 →