Skip to content
Tutorials Center
My learning

Topics

Lesson 123 of 201 ยท Input and Output

NIO.2: Path, Files and WatchService

Learn Java NIO.2 - Path operations like resolve and relativize, Files copy and move options, atomic moves, zip file systems and WatchService for reacting to folder changes.

When Java 7 arrived it brought a second file API, called NIO.2 (the package java.nio.file). It replaced the old java.io.File class, which had real weaknesses: methods that returned false without saying why, no symbolic-link support, no way to copy or move a file reliably, and no way to react when a folder changed. NIO.2 fixes all of that with three main pieces: Path (a location), Files (the actions) and WatchService (notifications).

You already used Path and Files for reading, writing and listing in Reading and Writing Files and Working with Directories. This lesson fills in the rest: building and comparing paths properly, copying and moving with the right options, safe "write then replace" updates, treating a zip file like a folder, and watching a directory for changes. Everything runs in a fresh temporary folder, so the output stays the same on each run.

Path: a location, not a file

A Path is only a name for a location. It doesn't have to exist, and creating one never touches the disk. Path.of(...) builds one from parts (the separator is added for you), and a handful of methods take it apart or combine it.

flowchart TD
    A["Path.of('/home/ada/docs/../notes/todo.txt')"] --> B["normalize()<br/>/home/ada/notes/todo.txt"]
    B --> C["getParent()<br/>/home/ada/notes"]
    B --> D["getFileName()<br/>todo.txt"]
    B --> E["relativize(/home/ada)<br/>notes/todo.txt"]

Path methods are pure text operations: none of them reads the disk.

Java Taking paths apart and putting them together

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Things worth remembering:

  • resolve appends a path to another one. If the argument is absolute, it wins and the base is ignored (the /tmp/x line). It's the safe replacement for gluing strings with "/".
  • relativize is the opposite: it computes how to get from one path to another. Both paths must be of the same kind (both absolute or both relative).
  • normalize removes . and resolves .. by text alone. It can't know about symbolic links, so on the real file system use toRealPath(), which also checks that the file exists and follows links.
  • A Path compares by its names, not by what is on disk. Use Files.isSameFile(a, b) to ask whether two paths reach the same file.
  • toString() uses the separator of the current system (\ on Windows). That's one reason to use resolve rather than building strings by hand.

Warning: When a path contains user input, never just resolve it onto your base folder and trust the result. A name like ../../etc/passwd escapes the folder. Normalize the result and check result.startsWith(base) before using it. This attack is called path traversal.

Files: quick reads and writes

Files is a class of static methods that do the work. For small files you rarely need streams at all:

Task Method
Whole file as text Files.readString(path) / Files.writeString(path, text)
All lines Files.readAllLines(path) / Files.write(path, lines)
Lazily process a big file try (Stream<String> s = Files.lines(path)) { ... }
Raw bytes Files.readAllBytes(path) / Files.write(path, bytes)
Buffered stream access Files.newBufferedReader(path) / Files.newBufferedWriter(path)
Exists, kind, size Files.exists, isDirectory, isRegularFile, size

Most of the writing methods take open options after the path: StandardOpenOption.APPEND adds to the end, CREATE_NEW fails if the file already exists, and TRUNCATE_EXISTING empties it first. By default, writeString creates the file or replaces its contents.

Copy and move, with the right options

Files.copy and Files.move are where NIO.2 beats the old API. Both refuse to overwrite an existing target unless you ask, and you pass options to say exactly what you want.

Java Copying and moving with options

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Two facts to take from this. First, copying a directory copies only the folder, not what's inside it. To copy a whole tree you walk it with Files.walkFileTree, as shown in Working with Directories. Second, Files.move is an ordinary rename when source and target are on the same drive, but across drives it has to copy and delete, which is no longer a single step. If you need the guarantee, ask for ATOMIC_MOVE; the call then fails with AtomicMoveNotSupportedException instead of silently falling back.

Safe updates: write a temp file, then move it

Imagine your program saves a settings file and the power fails halfway through the write. The result is a half-written, broken file, and the old content is gone. The professional pattern is:

  1. Write the new content to a temporary file in the same folder.
  2. Move it over the real file with ATOMIC_MOVE and REPLACE_EXISTING.

Readers then see either the whole old file or the whole new file, never a mixture.

Java Atomic replace

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The folder at the end contains only settings.properties: the temporary file was moved onto it. This pattern is the foundation of how many editors and databases avoid corrupt files.

A zip file as a file system

NIO.2 is built on the idea of a FileSystem: anything that offers paths and the Files operations. The default one is your disk, but the JDK also ships a zip/jar provider. Open an archive as a file system and you can use Files.copy, Files.walk and Files.readString on its contents as if it were a folder:

Java Writing and reading a zip like a folder

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Always close the zip file system (the try-with-resources does it): the archive is only completely written when it closes.

WatchService: reacting to changes

Polling a folder every second to see if something changed wastes CPU. A WatchService asks the operating system to tell you instead (on Linux this uses inotify). You register a directory for the events you care about, then wait for them:

sequenceDiagram
    participant App as Your code
    participant WS as WatchService
    participant OS as Operating system
    App->>WS: dir.register(ws, CREATE, MODIFY, DELETE)
    App->>WS: take() or poll(timeout)
    OS-->>WS: a file changed in dir
    WS-->>App: WatchKey with pending events
    App->>App: key.pollEvents() and handle each one
    App->>WS: key.reset()

You must call reset() on a key, or the service stops delivering events for that directory.

The three event kinds are ENTRY_CREATE, ENTRY_MODIFY and ENTRY_DELETE. Each WatchEvent has a kind() and a context(), which is the file name relative to the watched folder. Here the main thread changes a folder and a watcher collects the events:

Java Watching a folder for changes

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Look at the output. Creating and filling a file does not give just one event: you normally receive ENTRY_CREATE and then one or more ENTRY_MODIFY, because the file is first created empty and then written to. Event details vary by operating system, which is why the examples collect all events from a key before reporting.

A realistic watcher loop

In a real program the watcher runs on its own thread (often a virtual thread, see Virtual Threads and Structured Concurrency) and loops forever:

Java
while (true) {
    WatchKey key = watcher.take();               // blocks until something happens
    Path watchedDir = (Path) key.watchable();    // which folder this key belongs to

    for (WatchEvent<?> event : key.pollEvents()) {
        if (event.kind() == OVERFLOW) {
            continue;                            // events were lost: rescan the folder
        }
        Path changed = watchedDir.resolve((Path) event.context());
        System.out.println(event.kind() + ": " + changed);
    }

    if (!key.reset()) {
        break;                                   // folder deleted: the key is no longer valid
    }
}

Keep these rules in mind:

  • It's not recursive. Registering src does not watch src/main. To watch a tree, walk it and register every sub-folder, and register new folders when you see an ENTRY_CREATE for a directory.
  • OVERFLOW means the OS dropped events because you were too slow. Treat it as "something changed, rescan".
  • Events are hints, not a log. A single save in an editor can produce several events, and some editors write a temp file and rename it. Debounce: wait until events stop for a moment before reacting.
  • Don't act on a file the instant it appears. An ENTRY_CREATE can arrive while another process is still writing the file.
  • Close the service (try-with-resources) so the OS releases the watch.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does Path.of("/home/ada").resolve("/tmp/x") return?

    resolve joins relative arguments to the base, but an absolute argument replaces the base completely.
  2. 2. What does Files.copy(folder, target) do when folder is a directory with files in it?

    Files.copy never copies directory contents. Walk the tree with walkFileTree to copy a whole folder.
  3. 3. Why does the safe-save pattern write a temp file in the same folder and then move it with ATOMIC_MOVE?

    A rename within one file system is atomic, so a crash during the write can never leave a half-written target file.
  4. 4. A WatchService stops delivering events for a directory after the first batch. What is the most likely mistake?

    After you process a key's events you must call reset() so that the key goes back to the ready state and the service can queue more events.

Summary

  • Path is a location; resolve, relativize, normalize, getParent and getFileName work on text only. Files does the real work on disk.
  • Check any path built from user input with normalize() and startsWith(base) to prevent path traversal.
  • Files.copy and Files.move refuse to overwrite unless you pass REPLACE_EXISTING; copying a directory copies only the folder itself.
  • Write to a temp file in the same folder and ATOMIC_MOVE it into place for crash-safe saves.
  • FileSystems.newFileSystem opens a zip or jar so you can use the normal Files methods inside it; close it to finish writing.
  • WatchService delivers CREATE, MODIFY and DELETE events per directory (not recursive). Always call reset() on the key, handle OVERFLOW, and expect several events for one change.

Next: Running External Processes, where your Java program starts other programs and talks to them.