Safe file handling and atomicity
What you will learn
Safe file handling combines a narrow input policy, bounded I/O, controlled directories, and explicit failure behavior. Stage complete content before requesting an atomic move; atomic visibility and crash durability are different guarantees.
- Reject names outside a narrow fixture policy before I/O.
- Inspect symlink metadata without following the link.
- Stage and publish a file with explicit atomic-move failure handling.
Each example is a complete Main.java file. Use a fresh directory, javac --release 21 Main.java, then java Main. No external dependencies. Run in a fresh lab-owned working directory. Examples create a unique child directory and delete fixed fixture names in finally. Symlink and atomic-move examples require corresponding filesystem support. The item helper validates leaf names; bounded reads at most max plus one byte.
Reject an invalid leaf name
import java.io.*;import java.nio.*;import java.nio.channels.*;import java.nio.charset.StandardCharsets;import java.nio.file.*;import java.nio.file.attribute.BasicFileAttributes;import java.util.*;public class Main { static Path item(Path dir, String name) { if (!name.matches("[a-z]{1,12}\\.(txt|bin)")) { throw new IllegalArgumentException("Invalid fixture name"); } return dir.resolve(name); } static byte[] bounded(InputStream in, int max) throws IOException { if (max < 0 || max > 4096) throw new IllegalArgumentException("Invalid limit"); byte[] data = in.readNBytes(max + 1); if (data.length > max) throw new IOException("Too many bytes"); return data; }
public static void main(String[] args) throws Exception { Path dir = Files.createTempDirectory(Path.of("."), "java-io-"); try { System.out.println(item(dir,"a.txt").getFileName()); for(String name : List.of("../a.txt","nested/a.txt",".txt")) { try { item(dir,name); } catch (IllegalArgumentException e) { System.out.println("rejected"); } } } finally { for (String name : List.of("a.txt", "b.txt", "data.bin", "stage.txt", "link.txt")) { Files.deleteIfExists(dir.resolve(name)); } Files.delete(dir); } }}Expected output:
a.txtrejectedrejectedrejectedThe narrow allowlist excludes path syntax before any file open.
Trust boundaries
These examples accept only simple ASCII leaf names matching [a-z]{1,12}\.(txt|bin) in a fresh directory owned by the lab. For this fixture the directory has no hostile concurrent writers. Reject absolute paths, separators, traversal components and names outside the policy. A lexical startsWith check on normalized paths is not a security boundary: symlinks, parent components and concurrent replacement can change what an operation opens. Do not open arbitrary host files. In a real shared directory use OS-enforced isolation, directory-relative operations where SecureDirectoryStream is supported, appropriate no-follow options and an independently reviewed threat model. The lab does not implement a race-proof shared-directory sandbox.
Stage and move
Write a staging file in the same owned directory, close it, then request Files.move with ATOMIC_MOVE. If unsupported, fail rather than silently downgrade when atomic visibility is required. With ATOMIC_MOVE other options are ignored; replacement of an existing target is provider-specific. The example uses an absent target and private directory. An ordinary move may not be atomic and a failed non-atomic move may leave ambiguous state. CREATE_NEW combines the absence check and creation atomically, unlike exists followed by write.
Durability and limits
A successful atomic rename prevents readers from seeing a partially renamed entry, but does not guarantee persistence after power loss. FileChannel.force can request content or metadata persistence for local storage; directory durability, hardware and filesystem semantics require a separate platform-specific design. Avoid a check-then-open size test as the only limit; use bounded reading. Cleanup removes only stage and target fixtures. A symbolic-link test inspects a link with NOFOLLOW_LINKS and deletes the link itself; it never opens the link target. Symlink support varies by provider.
Request atomic publication
import java.io.*;import java.nio.*;import java.nio.channels.*;import java.nio.charset.StandardCharsets;import java.nio.file.*;import java.nio.file.attribute.BasicFileAttributes;import java.util.*;public class Main { static Path item(Path dir, String name) { if (!name.matches("[a-z]{1,12}\\.(txt|bin)")) { throw new IllegalArgumentException("Invalid fixture name"); } return dir.resolve(name); } static byte[] bounded(InputStream in, int max) throws IOException { if (max < 0 || max > 4096) throw new IllegalArgumentException("Invalid limit"); byte[] data = in.readNBytes(max + 1); if (data.length > max) throw new IOException("Too many bytes"); return data; }
public static void main(String[] args) throws Exception { Path dir = Files.createTempDirectory(Path.of("."), "java-io-"); try { Path stage=item(dir,"stage.txt"), target=item(dir,"a.txt"); Files.writeString(stage,"complete",StandardCharsets.UTF_8,StandardOpenOption.CREATE_NEW); try { Files.move(stage,target,StandardCopyOption.ATOMIC_MOVE); } catch (AtomicMoveNotSupportedException e) { throw new IOException("Atomic publication unavailable",e); } System.out.println(Files.readString(target)); System.out.println(Files.notExists(stage,LinkOption.NOFOLLOW_LINKS)); } finally { for (String name : List.of("a.txt", "b.txt", "data.bin", "stage.txt", "link.txt")) { Files.deleteIfExists(dir.resolve(name)); } Files.delete(dir); } }}Expected output:
completetrueOn the tested local provider the move succeeded. On unsupported providers this example fails explicitly; it never retries non-atomically.
Inspect a link without following it
import java.io.*;import java.nio.*;import java.nio.channels.*;import java.nio.charset.StandardCharsets;import java.nio.file.*;import java.nio.file.attribute.BasicFileAttributes;import java.util.*;public class Main { static Path item(Path dir, String name) { if (!name.matches("[a-z]{1,12}\\.(txt|bin)")) { throw new IllegalArgumentException("Invalid fixture name"); } return dir.resolve(name); } static byte[] bounded(InputStream in, int max) throws IOException { if (max < 0 || max > 4096) throw new IllegalArgumentException("Invalid limit"); byte[] data = in.readNBytes(max + 1); if (data.length > max) throw new IOException("Too many bytes"); return data; }
public static void main(String[] args) throws Exception { Path dir = Files.createTempDirectory(Path.of("."), "java-io-"); try { Path file=item(dir,"a.txt"), link=item(dir,"link.txt"); Files.writeString(file,"owned"); Files.createSymbolicLink(link,Path.of("a.txt")); var attrs=Files.readAttributes(link,BasicFileAttributes.class,LinkOption.NOFOLLOW_LINKS); System.out.println(attrs.isSymbolicLink()); Files.delete(link); System.out.println(Files.readString(file)); } finally { for (String name : List.of("a.txt", "b.txt", "data.bin", "stage.txt", "link.txt")) { Files.deleteIfExists(dir.resolve(name)); } Files.delete(dir); } }}Expected output:
trueownedThe target is read through its original known path, never via the link. This fixture requires local symlink support.
Reject oversize data and retain original
import java.io.*;import java.nio.*;import java.nio.channels.*;import java.nio.charset.StandardCharsets;import java.nio.file.*;import java.nio.file.attribute.BasicFileAttributes;import java.util.*;public class Main { static Path item(Path dir, String name) { if (!name.matches("[a-z]{1,12}\\.(txt|bin)")) { throw new IllegalArgumentException("Invalid fixture name"); } return dir.resolve(name); } static byte[] bounded(InputStream in, int max) throws IOException { if (max < 0 || max > 4096) throw new IllegalArgumentException("Invalid limit"); byte[] data = in.readNBytes(max + 1); if (data.length > max) throw new IOException("Too many bytes"); return data; }
public static void main(String[] args) throws Exception { Path dir = Files.createTempDirectory(Path.of("."), "java-io-"); try { Path file=item(dir,"a.txt"), stage=item(dir,"stage.txt"); Files.writeString(file,"original"); Files.writeString(stage,"too long"); try (InputStream in=Files.newInputStream(stage)) { bounded(in,4); } catch (IOException e) { System.out.println("rejected"); } finally { Files.deleteIfExists(stage); } System.out.println(Files.readString(file)); System.out.println(Files.notExists(stage,LinkOption.NOFOLLOW_LINKS)); } finally { for (String name : List.of("a.txt", "b.txt", "data.bin", "stage.txt", "link.txt")) { Files.deleteIfExists(dir.resolve(name)); } Files.delete(dir); } }}Expected output:
rejectedoriginaltrueValidation fails before any publication attempt. The original remains intact.
Common mistakes
Do not treat normalize or an existence check as proof of safety. Never silently replace an atomic move with copy-and-delete. Do not claim crash durability from an atomic rename. Do not follow links or recursively clean up unknown paths.
Practice
Create stage.txt with text ready using CREATE_NEW and publish to the absent b.txt with ATOMIC_MOVE. Print the published text and whether the staging file is absent. Fail if atomic move is unavailable and clean up fixed paths.
Expected output:
readytrueCompare your answer with the manual practice criteria.
Official reading: Files · Path · SecureDirectoryStream. Java 25 execution remains unverified.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Safe file handling and atomicity — knowledge check
Original filesystem and I/O questions. Java 21-compatible scope.
Does normalize prevent symlink escapes?
What should happen if ATOMIC_MOVE is unsupported but required?
What if an ATOMIC_MOVE target already exists?
Does an atomic move guarantee power-loss durability?
What bounds the small input read here?