Write files safely
40 min · Advanced
Need help? Ask a tutor on WhatsApp (opens in a new tab)Showing steps for Windows. They are marked “On Windows” below.
A program that saves bookings, marks or settings must never leave the file broken, even if it crashes halfway through a save. The safe pattern is short: back up the old file, write the new one to a temporary file, then swap it in with a single atomic move.
The half-written file after a crash
A half-written file is what a direct write leaves behind when the program stops in the middle. Files.writeString and newBufferedWriter open the target with TRUNCATE_EXISTING, which empties it at once; the new text is written after that.
Example 1 · A crash halfway through a normal write
import java.io.BufferedWriter;import java.io.IOException;import java.nio.charset.StandardCharsets;import java.nio.file.Files;import java.nio.file.Path;import java.util.List;
public class HalfWrittenDemo { // Writes the rows straight into the target; "crashes" before row number crashAt static void saveMarks(Path file, List<String> rows, int crashAt) throws IOException { try (BufferedWriter out = Files.newBufferedWriter(file, StandardCharsets.UTF_8)) { for (int i = 0; i < rows.size(); i++) { if (i == crashAt) { throw new IOException("simulated crash while saving"); } out.write(rows.get(i)); out.write("\n"); } } }
public static void main(String[] args) throws IOException { Path file = Path.of("marks.csv"); Files.writeString(file, "Asha,86\nRavi,72\nMeena,91\nKiran,64\n"); // last good save System.out.println("Before: " + Files.readAllLines(file));
try { saveMarks(file, List.of("Asha,88", "Ravi,75", "Meena,93", "Kiran,66"), 2); } catch (IOException e) { System.out.println("Save failed: " + e.getMessage()); } System.out.println("After: " + Files.readAllLines(file));
Files.delete(file); }}Before: [Asha,86, Ravi,72, Meena,91, Kiran,64] Save failed: simulated crash while saving After: [Asha,88, Ravi,75]
What this code does
- Opening the writer emptied the old file at once (
TRUNCATE_EXISTING). When the save failed after two rows, Meena's and Kiran's marks were gone: neither the old nor the new version survived. - Here the exception still let try-with-resources flush two rows. A real power cut or a killed process can leave even less: an empty file or half a line.
If the program crashes, is killed, or the laptop loses power between those steps, the old data is already gone and the new data is incomplete. For a log you append to, this risk is small. For a file you rewrite completely, such as all hostel bookings, it can lose everything.
Write to a temporary file, then ATOMIC_MOVE
An atomic operation happens completely or not at all: no other program can ever see it half done. A rename done with ATOMIC_MOVE is atomic.
An atomic operation happens completely or not at all. Files.move(temp, target, StandardCopyOption.ATOMIC_MOVE) renames the finished temporary file over the target in one step, so anyone opening the target sees the full old version or the full new version, never a mix.
Example 2 · Write to a temporary file, then ATOMIC_MOVE
import java.io.BufferedWriter;import java.io.IOException;import java.nio.charset.StandardCharsets;import java.nio.file.Files;import java.nio.file.Path;import java.nio.file.StandardCopyOption;import java.util.List;import java.util.stream.Stream;
public class AtomicSaveDemo { static void saveAtomically(Path target, List<String> rows, int crashAt) throws IOException { Path dir = target.toAbsolutePath().getParent(); Path temp = Files.createTempFile(dir, "marks-", ".tmp"); try { try (BufferedWriter out = Files.newBufferedWriter(temp, StandardCharsets.UTF_8)) { for (int i = 0; i < rows.size(); i++) { if (i == crashAt) { throw new IOException("simulated crash while saving"); } out.write(rows.get(i)); out.write("\n"); } } Files.move(temp, target, StandardCopyOption.ATOMIC_MOVE); } finally { Files.deleteIfExists(temp); // removes the temp file if the move did not happen } }
static List<String> names(Path dir) throws IOException { try (Stream<Path> files = Files.list(dir)) { return files.map(p -> p.getFileName().toString()).sorted().toList(); } }
public static void main(String[] args) throws IOException { Path dir = Files.createTempDirectory("safe-save"); Path marks = dir.resolve("marks.csv"); Files.writeString(marks, "Asha,86\nRavi,72\nMeena,91\nKiran,64\n"); List<String> newRows = List.of("Asha,88", "Ravi,75", "Meena,93", "Kiran,66");
try { saveAtomically(marks, newRows, 2); } catch (IOException e) { System.out.println("Save failed: " + e.getMessage()); } System.out.println("After crash: " + Files.readAllLines(marks)); System.out.println("Folder: " + names(dir));
saveAtomically(marks, newRows, -1); // -1: no crash this time System.out.println("After save: " + Files.readAllLines(marks)); System.out.println("Folder: " + names(dir));
Files.delete(marks); Files.delete(dir); }}Save failed: simulated crash while saving After crash: [Asha,86, Ravi,72, Meena,91, Kiran,64] Folder: [marks.csv] After save: [Asha,88, Ravi,75, Meena,93, Kiran,66] Folder: [marks.csv]
What this code does
- All writing goes to a temporary file in the same folder. The crash hit only that file;
finallydeleted it, andmarks.csvstill holds the last good save. - On success,
Files.movewithATOMIC_MOVEswaps the new file in with one rename. Anyone readingmarks.csvsees either the old version or the new one, never a mix. After the move the temp file no longer exists, sodeleteIfExistsdoes nothing.
Create the temp file in the same folder as the target, with Files.createTempFile(folder, prefix, suffix): an atomic rename works only within one drive, and across drives Java throws AtomicMoveNotSupportedException. Delete the temp file in finally with deleteIfExists, so a failed save leaves no clutter.
In order: write everything to the temp file and close it, then move it over the target with ATOMIC_MOVE.
Order of execution
Order of a safe save
Put the steps in the order the program runs them.
Keeping a backup copy
A backup copy is the previous version of the file, kept next to it, for example marks.csv.bak. Make it with Files.copy(target, backup, StandardCopyOption.REPLACE_EXISTING) just before you replace the target.
Example 3 · Keeping a backup copy
import java.io.IOException;import java.nio.charset.StandardCharsets;import java.nio.file.Files;import java.nio.file.Path;import java.nio.file.StandardCopyOption;
public class BackupSaveDemo { static void saveWithBackup(Path target, String content) throws IOException { if (Files.exists(target)) { Path backup = target.resolveSibling(target.getFileName() + ".bak"); Files.copy(target, backup, StandardCopyOption.REPLACE_EXISTING); } Path temp = Files.createTempFile(target.toAbsolutePath().getParent(), "save-", ".tmp"); try { Files.writeString(temp, content, StandardCharsets.UTF_8); Files.move(temp, target, StandardCopyOption.ATOMIC_MOVE); } finally { Files.deleteIfExists(temp); } }
public static void main(String[] args) throws IOException { Path dir = Files.createTempDirectory("backup-demo"); Path marks = dir.resolve("marks.csv"); Path backup = dir.resolve("marks.csv.bak");
saveWithBackup(marks, "Asha,85\n"); saveWithBackup(marks, "Asha,90\n"); saveWithBackup(marks, "Asha,9\n"); // typing mistake: 9 instead of 95
System.out.print("marks.csv: " + Files.readString(marks)); System.out.print("marks.csv.bak: " + Files.readString(backup));
Files.copy(backup, marks, StandardCopyOption.REPLACE_EXISTING); System.out.print("Restored: " + Files.readString(marks));
Files.delete(marks); Files.delete(backup); Files.delete(dir); }}marks.csv: Asha,9 marks.csv.bak: Asha,90 Restored: Asha,90
What this code does
- Before each save, the current file is copied to
marks.csv.bak. A crash cannot hurt the backup, and a wrong save, like the typing mistake here, can be undone. REPLACE_EXISTINGlets each save overwrite the previous backup, so you always have exactly one step of history. Restoring is just a copy back.
The atomic move protects you from crashes; the backup protects you from saving wrong data, such as a typing mistake or a bug. Restoring is a single copy back. Apps that need more history keep several numbered backups and rotate them.
Disk full and permission errors while writing
Writes can fail for reasons your code cannot prevent. AccessDeniedException means the operating system refused: the file is read-only, belongs to another user, or is locked by another program. A full disk shows up as an IOException.
On Windows
Windows locks a file that another program has open, such as a spreadsheet in Excel. A save or an ATOMIC_MOVE over it fails, often with a message like "The process cannot access the file because it is being used by another process". Ask the user to close the file and try again.
Example 4 · Permission errors while writing
import java.io.IOException;import java.nio.file.AccessDeniedException;import java.nio.file.Files;import java.nio.file.Path;
public class ReadOnlyDemo { public static void main(String[] args) throws IOException { Path dir = Files.createTempDirectory("perm-demo"); Path file = dir.resolve("timetable.txt"); Files.writeString(file, "Mon: Maths\n"); file.toFile().setReadOnly(); // like a file marked read-only by the college IT team
try { Files.writeString(file, "Mon: Physics\n"); } catch (AccessDeniedException e) { System.out.println("AccessDeniedException: cannot write " + file.getFileName()); } catch (IOException e) { System.out.println("Other write error: " + e); } System.out.print("Content is still: " + Files.readString(file));
file.toFile().setWritable(true); Files.delete(file); Files.delete(dir); }}AccessDeniedException: cannot write timetable.txt Content is still: Mon: Maths
What this code does
AccessDeniedException(a subclass ofIOException) means the operating system refused: the file is read-only, belongs to another user, or, on Windows, is locked by another program.- Opening failed before anything was written, so the old content is untouched.
toFile()gives the oldjava.io.Fileview of the path, which has the simplesetReadOnlyandsetWritablemethods used here.
The full-disk message comes from the operating system: "No space left on device" on Linux and macOS, "There is not enough space on the disk" on Windows.
Catch these around the whole save. Tell the user in plain words what failed and that the previous data is still safe, which the temp-then-move pattern guarantees. Never leave a half-finished temp file in place of the real one.
IOException, so put the specific catch (AccessDeniedException e) before catch (IOException e).Example 5 · All together: a safe save with a clear message
import java.io.IOException;import java.nio.charset.StandardCharsets;import java.nio.file.AccessDeniedException;import java.nio.file.AtomicMoveNotSupportedException;import java.nio.file.Files;import java.nio.file.Path;import java.nio.file.StandardCopyOption;import java.util.List;
public class SafeSaverDemo { static boolean diskFull = false; // switch to simulate a full disk
static void writeAll(Path file, List<String> rows) throws IOException { StringBuilder sb = new StringBuilder(); for (String row : rows) { sb.append(row).append("\n"); } if (diskFull) { throw new IOException("No space left on device"); } Files.writeString(file, sb.toString(), StandardCharsets.UTF_8); }
static boolean save(Path target, List<String> rows) { Path temp = null; try { if (Files.exists(target)) { Files.copy(target, target.resolveSibling(target.getFileName() + ".bak"), StandardCopyOption.REPLACE_EXISTING); } temp = Files.createTempFile(target.toAbsolutePath().getParent(), "save-", ".tmp"); writeAll(temp, rows); try { Files.move(temp, target, StandardCopyOption.ATOMIC_MOVE); } catch (AtomicMoveNotSupportedException e) { Files.move(temp, target, StandardCopyOption.REPLACE_EXISTING); } System.out.println("Saved " + rows.size() + " bookings."); return true; } catch (AccessDeniedException e) { System.out.println("Could not save: no permission to write " + target.getFileName() + "."); } catch (IOException e) { System.out.println("Could not save: " + e.getMessage() + ". Your previous data is safe."); } finally { if (temp != null) { try { Files.deleteIfExists(temp); } catch (IOException ignored) { // the temp file may stay behind; the real file is fine } } } return false; }
public static void main(String[] args) throws IOException { Path dir = Files.createTempDirectory("bookings"); Path file = dir.resolve("bookings.csv");
save(file, List.of("Asha,Room 101", "Ravi,Room 102")); diskFull = true; save(file, List.of("Asha,Room 101", "Ravi,Room 102", "Meena,Room 103")); System.out.println("File has: " + Files.readAllLines(file));
Files.delete(file); Files.delete(dir.resolve("bookings.csv.bak")); Files.delete(dir); }}Saved 2 bookings. Could not save: No space left on device. Your previous data is safe. File has: [Asha,Room 101, Ravi,Room 102]
What this code does
- The method combines every step: backup, write to a temp file, atomic move (with a plain move as a fallback), clear messages, and cleanup in
finally. - A full disk cannot be created on purpose in a demo, so
writeAllthrows the same message Linux gives. The second save fails, the user is told plainly, and the two saved bookings are untouched.
Next step
Check your understanding
11 quick questions