A Java application writes sensitive user data to a file. To ensure that data is not left in the file system after the application crashes, which practice should be followed?
Atomic move ensures the target file is either fully written or not replaced, preventing partial writes.
Why this answer
Writing to a temporary file and then atomically moving it with `Files.move()` using the `ATOMIC_MOVE` option ensures that the target file is replaced only after the write succeeds. If the application crashes during the write, only the temporary file is corrupted, and the original target file remains intact. This prevents sensitive data from being left in an incomplete or partially written state in the file system.
Exam trap
The trap here is that candidates often confuse data flushing or locking with crash-safe file updates, but neither `flush()` nor `FileLock` provides atomicity guarantees, which is the key requirement for preventing data corruption after a crash.
How to eliminate wrong answers
Option A is wrong because calling `flush()` only forces buffered data to the underlying stream but does not guarantee that the data is fully written to disk or that the file is not left in an inconsistent state after a crash. Option B is wrong because manually deleting the file in a `finally` block cannot execute if the JVM crashes or the application is killed abruptly, leaving the sensitive data on disk. Option C is wrong because a `FileLock` prevents concurrent access from other JVM processes but does not protect against data loss or incomplete writes during a crash.