Java

Atomic File Write (move with ATOMIC_MOVE)

admin by @admin ADMIN
1d ago
May 31, 2026
Public
0 0 up · 0 down Sign in to vote
Write to a temp file in the same directory, then `Files.move` with `ATOMIC_MOVE` to the target. Readers never see a half-written file — critical for config / state files.
Java
Raw
import java.io.IOException;
import java.nio.file.*;
import static java.nio.file.StandardCopyOption.*;

class Demo {
    static void atomicWrite(Path target, byte[] data) throws IOException {
        Path tmp = Files.createTempFile(target.getParent(),
            "." + target.getFileName() + ".", ".tmp");
        try {
            Files.write(tmp, data);
            Files.move(tmp, target,
                ATOMIC_MOVE, REPLACE_EXISTING);
        } catch (IOException e) {
            Files.deleteIfExists(tmp);
            throw e;
        }
    }

    public static void main(String[] args) throws IOException {
        atomicWrite(Path.of("/var/lib/myapp/state.json"),
            "{\"ready\":true}\n".getBytes());
    }
}
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.