Library contents

Java Files.createFile

Reserve a fresh filename atomically by creating an empty file.

A simple example

Files.createFile

  1. Start with An unused name a.txt
  2. Do this Create exclusively twice
  3. Result First succeeds, second fails
The second attempt encounters the file created by the first.

Syntax

Java 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.java

Issue 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.

ResultTicket already issued
Main.java
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);
            }
        }
    }
}
Output
Ticket already issued

The exception identifies a name collision at the operation that actually creates the ticket.

Advertisements

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.

First output linetrue
Main.java
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);
            }
        }
    }
}
Output
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?

GivenFile contents “clay”
Worked resultOriginal kept

What to watch for

A prior exists check cannot guarantee the name is still available when a second process attempts creation.

Documentation for Files.createFile