Java Tutorial · Advanced Java · Lesson 35 of 37

Java File Handling

Read and write files with java.nio.file.Files and Path.

Files and Path

The modern file API lives in java.nio.file. Path represents a file location; Files has static methods to read, write, copy and delete:

Example 1
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardOpenOption;
import java.util.List;
import java.util.stream.Stream;

public class Main {
    public static void main(String[] args) throws IOException {
        Path file = Files.createTempFile("notes", ".txt");
        Files.writeString(file, "first line\n");
        Files.writeString(file, "second line\n", StandardOpenOption.APPEND);
        Files.write(file, List.of("third line", "fourth line"), StandardOpenOption.APPEND);
        List<String> lines = Files.readAllLines(file);
        System.out.println(lines.size() + " lines, first: " + lines.get(0));
        try (Stream<String> stream = Files.lines(file)) {
            System.out.println(stream.filter(l -> l.startsWith("t")).toList());
        }
        System.out.println(Files.exists(file) + " " + Files.size(file) + " bytes");
        Files.delete(file);
        System.out.println(Files.exists(file));
    }
}

Output

4 lines, first: first line
[third line]
true 46 bytes
false

Run this on your computer — see “Get Started” for setup.

Large files

Files.readAllLines() loads everything into memory. For big files, stream the lines lazily with Files.lines() inside try-with-resources, or use a BufferedReader.

File operations throw the checked IOException — handle it, or declare throws IOException as in this example.

Test yourself

Which checked exception do most file operations throw?

  1. FileError
  2. IOException
  3. NullPointerException
  4. RuntimeException
Show answer

Answer: IOException