Sub topic 15
Writing safely with a temporary file
This chapter assumes you know basic Java classes, checked exceptions, and try-with-resources. It also assumes you can use Path and Files from java.nio.file.
A normal write can leave a target file incomplete. For example, a program might truncate report.txt, write half of its content, and then stop because of an exception or power failure. A reader that opens the file during that interval sees partial data.
A safe write separates preparation from publication:
- Create a temporary file in the target directory.
- Write the complete content to the temporary file.
- Move the temporary file to the final path.
- Replace the old file during the move.
The final path changes only after the new content has been written.
The temporary-file pattern
import java.io.IOException;
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 SafeWrite {
public static void main(String[] args) throws IOException {
Path target = Path.of("out", "report.txt").toAbsolutePath();
Path directory = target.getParent();
Files.createDirectories(directory);
Path temporary = Files.createTempFile(directory, "report-", ".tmp");
try {
Files.writeString(
temporary,
"Report completed\n",
StandardCharsets.UTF_8,
StandardOpenOption.WRITE,
StandardOpenOption.TRUNCATE_EXISTING);
try {
Files.move(
temporary,
target,
StandardCopyOption.ATOMIC_MOVE,
StandardCopyOption.REPLACE_EXISTING);
} catch (AtomicMoveNotSupportedException e) {
Files.move(
temporary,
target,
StandardCopyOption.REPLACE_EXISTING);
}
} finally {
Files.deleteIfExists(temporary);
}
}
}The temporary file is created in the same directory as the target. This matters because an atomic move usually requires both paths to be on the same file system. CREATE_TEMP_FILE also chooses a unique name, which avoids collisions between concurrent program runs.
ATOMIC_MOVE asks the file system to publish the temporary file as one indivisible operation. A reader sees either the old file or the complete new file. It should not see the intermediate temporary content. Some file systems do not support this operation, so Java throws AtomicMoveNotSupportedException. The fallback still writes the complete temporary file before moving it, but the replacement itself might not be atomic.
Failure handling and cleanup
If writing the temporary file fails, the original target remains unchanged. The finally block removes the temporary file whether the move succeeds, fails, or is unsupported.
The move can still fail because the directory is read-only, permissions changed, the target is locked, or the disk is full. Catching IOException at a higher level lets the application report that the update did not complete. Do not delete the original file first. That creates a period in which no valid target exists.
Exercise
Why should the temporary file be created in the target directory instead of a system-wide temporary directory?
Show answer
The same directory usually keeps both paths on the same file system, which allows an atomic move and avoids a cross-file-system move failure.