Sub topic 15
Writing safely with a temporary file
This chapter assumes you can use Path and Files, write whole files with Files.writeString, create directories, and use Files.move. It also assumes you know how checked exceptions work. You need Java 11 or later.
The problem with writing in place
Files.writeString(target, text) opens the target with CREATE, TRUNCATE_EXISTING and WRITE. The old content is destroyed at the moment the file is opened, before your new content is written. If the process crashes, the disk fills up, or the JVM is killed halfway through, the file is left empty or partly written.
A second problem affects other programs. A reader that opens the file while you are writing can see a half-written version. This matters for configuration files, caches, reports that other tools pick up, and any data you cannot easily regenerate.
The fix is to never modify the real file directly. Write the complete new content to a temporary file, then replace the real file with one move operation. The target then holds either the old content or the new content, and never a mixture.
The basic pattern
This is the pattern from the topic plan, shown as a complete program:
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;
public class SafeWrite {
public static void main(String[] args) throws IOException {
Path target = Path.of("out", "report.txt");
Path dir = target.toAbsolutePath().getParent();
Files.createDirectories(dir);
Path temp = Files.createTempFile(dir, "report", ".tmp");
Files.writeString(temp, "done\n");
Files.move(temp, target, StandardCopyOption.ATOMIC_MOVE);
}
}Each step has a reason:
toAbsolutePath().getParent()gives the directory that will hold the target. A relative path such asreport.txthas no parent, sogetParent()would returnnull. Converting to an absolute path first avoids that.Files.createDirectories(dir)creates the directory if it is missing and does nothing if it already exists.Files.createTempFile(dir, prefix, suffix)creates a new, empty file with a unique name insidedir.Files.writeString(temp, ...)writes the content. Truncation is harmless here because the temp file is private to your program.Files.move(..., ATOMIC_MOVE)renames the temp file to the target name in one step.
Why the temp file must be in the same directory
The one-argument form Files.createTempFile(prefix, suffix) puts the file in the system temp directory, such as /tmp. That directory is often on a different file system or partition than your target. Moving across file systems cannot be a rename. The data has to be copied, and a copy is not atomic. A crash during that copy gives you the same half-written file you were trying to avoid.
Creating the temp file next to the target keeps both on the same file system. The move then becomes a rename, which the operating system performs as a single operation.
What ATOMIC_MOVE guarantees
StandardCopyOption.ATOMIC_MOVE asks for a move that is a single indivisible step. Any other process watching the directory sees either the old state or the new state. Two details matter:
- If the file system cannot do an atomic move,
Files.movethrowsAtomicMoveNotSupportedException. It does not quietly fall back to a copy. - If the target already exists, the
Files.movedocumentation says it is implementation specific whether the target is replaced or anIOExceptionis thrown. On Linux and macOS the underlying rename replaces the target. On Windows the JDK also replaces it, but you should not depend on this for portable code.
You cannot combine ATOMIC_MOVE with REPLACE_EXISTING in a way that adds a guarantee. When ATOMIC_MOVE is present, other copy options are ignored.
A reusable helper
Production code needs more than the basic pattern. It should delete the temp file when something fails, flush the data to disk before the rename, and handle file systems without atomic moves. This helper does all three:
import java.io.IOException;
import java.nio.channels.FileChannel;
import java.nio.charset.StandardCharsets;
import java.nio.file.AtomicMoveNotSupportedException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;
import java.nio.file.StandardOpenOption;
public class AtomicWriter {
public static void writeAtomically(Path target, String content) throws IOException {
Path absolute = target.toAbsolutePath();
Path dir = absolute.getParent();
Files.createDirectories(dir);
Path temp = Files.createTempFile(dir, absolute.getFileName().toString(), ".tmp");
try {
Files.writeString(temp, content, StandardCharsets.UTF_8);
try (FileChannel channel = FileChannel.open(temp, StandardOpenOption.WRITE)) {
channel.force(true);
}
try {
Files.move(temp, absolute, StandardCopyOption.ATOMIC_MOVE);
} catch (AtomicMoveNotSupportedException e) {
Files.move(temp, absolute, StandardCopyOption.REPLACE_EXISTING);
}
} finally {
Files.deleteIfExists(temp);
}
}
public static void main(String[] args) throws IOException {
Path file = Path.of("out", "settings.txt");
writeAtomically(file, "version=1\n");
writeAtomically(file, "version=2\n");
System.out.print(Files.readString(file));
}
}Running it prints version=2. The directory out contains only settings.txt, with no .tmp files left over.
How the helper behaves
- The
finallyblock. If the write or the move throws, the temp file is deleted so failures do not litter the directory. After a successful move the temp path no longer exists, sodeleteIfExistsreturnsfalseand does nothing. channel.force(true).Files.writeStringreturns once the data is handed to the operating system, not once it is on the disk. Without a flush, a power failure just after the rename can leave a correctly named file with missing content.force(true)asks the OS to write the data and metadata to the storage device. It costs time, so skip it for data you can regenerate.- The fallback. If the atomic move is not supported, the helper retries with
REPLACE_EXISTING. This is no longer atomic, so use it only when a rare window of inconsistency is acceptable. Otherwise, let the exception propagate.
Failure modes and gotchas
| Situation | What happens | What to do |
|---|---|---|
| Crash before the move | The old target is untouched, and a stale `.tmp` file remains | Delete leftover `*.tmp` files at startup |
| Crash after the move | The new target is in place | Nothing |
| Temp file in a different file system | `ATOMIC_MOVE` throws, or a plain move copies non-atomically | Create the temp file in the target's directory |
| Target directory does not exist | `createTempFile` throws `NoSuchFileException` | Call `Files.createDirectories` first |
| Two writers target the same file | The last move wins and the other update is lost | Add locking or a single writer |
| Target is open in another program | On Windows the move can fail with `AccessDeniedException` or `FileSystemException` | Retry or report the error |
Atomic replacement also changes the identity of the file:
- Permissions. On POSIX systems,
createTempFilecreates files readable and writable only by the owner (mode 600). The new target gets those permissions even if the old target was world-readable. Copy the old permissions to the temp file withFiles.setPosixFilePermissionsif they matter. - Hard links and symbolic links. Replacing the target by rename breaks hard links to the old file. They keep pointing at the old content. If the target is a symbolic link, the move replaces the link itself, not the file it points to.
- Ownership and extended attributes. They are not carried over to the new file.
If you need to keep the file's identity, such as a log file shared through hard links, write in place and accept the crash risk, or use a different strategy such as an append-only log.
When to use this pattern
Use it when the file is read by other programs or by your own program after a restart, and a partial file would cause harm. Examples are configuration, state files, indexes, and generated reports.
Do not use it for append-only files such as logs, where each write adds to the end and a partial last line is a known and tolerable failure. Do not use it for files so large that writing a full second copy is too costly in disk space or time.
Exercise
Why does the helper call Files.deleteIfExists(temp) in a finally block, even though a successful Files.move already removes the temp path?
Show answer
The finally block covers failure paths. If writeString, force or the move throws, the temp file still exists and would be left behind. After a successful move, the temp path no longer exists, so deleteIfExists returns false and does nothing. One cleanup statement therefore handles both outcomes.
Exercise
A developer calls Files.createTempFile("cfg", ".tmp"), writes the content, and moves the result onto /data/app/config.txt with ATOMIC_MOVE. On the production server this throws an exception, though it works on the developer's laptop. What is the likely cause, and how do you fix it?
Show answer
The temp file went into the system temp directory, such as /tmp, which on the server is on a different file system from /data/app. An atomic move cannot cross file systems, so Files.move throws AtomicMoveNotSupportedException. On the laptop both locations were probably on the same file system. Fix it by creating the temp file in the target's directory: Files.createTempFile(target.toAbsolutePath().getParent(), "config", ".tmp").
Exercise
Write a method signature and the single line of code that makes the new target keep the same POSIX permissions as the old one, assuming the old target exists. State where in the helper the line belongs.
Show answer
Add Files.setPosixFilePermissions(temp, Files.getPosixFilePermissions(absolute)); after the content is written and before the move. The method is static void writeAtomically(Path target, String content) throws IOException. It must run only if the target exists and the file system supports POSIX attributes, so guard it with Files.exists(absolute) and catch UnsupportedOperationException on non-POSIX systems.