Video in progress

Strong Middle 📁 IO and NIO

Write a file so that even if the process crashes in the middle of writing, a reader never sees a half-written file.

Write the new content to a temporary file in the same directory, push it to disk with force(true), then swap it into the real name with Files.move(..., ATOMIC_MOVE). A rename is atomic: the reader sees either the old file or the new one, complete.

📖 Answer

Writing directly over the file is risky: TRUNCATE_EXISTING empties the file immediately, and a crash in the middle of the write leaves it empty or half done.

static void writeAtomically(Path target, byte[] data) throws IOException {
    Path dir = target.toAbsolutePath().getParent();
    Path tmp = Files.createTempFile(dir, ".tmp-", null); // in the same directory!
    try {
        try (FileChannel ch = FileChannel.open(tmp, StandardOpenOption.WRITE)) {
            ByteBuffer buf = ByteBuffer.wrap(data);
            while (buf.hasRemaining()) ch.write(buf);
            ch.force(true);                   // from the OS cache to disk
        }
        Files.move(tmp, target, StandardCopyOption.ATOMIC_MOVE,
                                StandardCopyOption.REPLACE_EXISTING);
    } finally {
        Files.deleteIfExists(tmp);           // on success this file is already gone
    }
}

Why in this very directory: a rename is atomic only within one file system. If /tmp is on a different disk, ATOMIC_MOVE throws an exception.

The subtle part: force guarantees only the file contents. For the rename itself to survive a power loss, the directory needs an fsync too. Java has no standard API for that; on Linux, opening the directory with FileChannel.open(dir, READ) and calling force(true) usually works, but that is platform-specific behavior.

For configuration, checkpoints and small state files, this is enough. For large, frequently updated data, use a DB or an append-only log.