Java Files.createFile
Reserve a fresh filename atomically by creating an empty file.
A simple example
Files.createFile
- Start with An unused name a.txt
- Do this Create exclusively twice
- Result First succeeds, second fails
Syntax
public static Path createFile(Path path, FileAttribute<?>... attrs) throws IOException
JDK 21 declarations (1)
Run these examples in Java
Save one example at a time as Main.java. Use JDK 21.
java Main.javaIssue a single claim ticket
Two clerks might try to issue the same numbered ticket. Attempt to reserve the name twice and handle the second reservation explicitly so the first clerk's ticket stays intact.
import java.nio.file.*;
class Main {
public static void main(String[] args) throws Exception {
Path desk = Files.createTempDirectory("file-lesson-");
try {
Path ticket = desk.resolve("claim-17");
Files.createFile(ticket);
try {
Files.createFile(ticket);
} catch (FileAlreadyExistsException e) {
System.out.println("Ticket already issued");
}
} finally {
try (var paths = Files.walk(desk)) {
for (Path p : paths.sorted(java.util.Comparator.reverseOrder()).toList())
Files.deleteIfExists(p);
}
}
}
}
Ticket already issued
The exception identifies a name collision at the operation that actually creates the ticket.
Check the contents of a fresh order marker
A dispatch desk uses the presence of a marker file to claim an order before writing details. Immediately after reservation, the marker should exist and have no payload.
import java.nio.file.*;
class Main {
public static void main(String[] args) throws Exception {
Path desk = Files.createTempDirectory("file-lesson-");
try {
Path claim = Files.createFile(desk.resolve("order-52"));
System.out.println(Files.isRegularFile(claim));
System.out.println(Files.size(claim));
} finally {
try (var paths = Files.walk(desk)) {
for (Path p : paths.sorted(java.util.Comparator.reverseOrder()).toList())
Files.deleteIfExists(p);
}
}
}
}
true 0
Creating a fresh file reserves its name and starts it at zero bytes.
Prepare a gallery label
A curator stores a short UTF-8 caption beside an exhibit. Two desks try to reserve the same filename using exclusive creation. What happens to the first successful reservation when the second desk tries?
What to watch for
A prior exists check cannot guarantee the name is still available when a second process attempts creation.