Java FileAlreadyExistsException
Creating a file with a name that already exists can raise FileAlreadyExistsException. An exclusive create operation protects the earlier report.
A simple example
FileAlreadyExistsException
- Start with A file named a.txt already exists
- Do this Try exclusive creation at the same name
- Result Creation fails
Syntax
Files.createFile(report)
Run these examples in Java
Save one example at a time as Main.java. Use JDK 21.
java Main.javaSave a report without replacing the first copy
Two shifts try to save their report under the same filename. The second shift needs to learn that the name is taken while the first shift's report stays available.
import java.nio.file.Files;
import java.nio.file.FileAlreadyExistsException;
class Main {
public static void main(String[] args) throws Exception {
var report = Files.createTempFile("shift-", ".txt");
try {
Files.createFile(report);
} catch (FileAlreadyExistsException taken) {
System.out.println("Choose a new report name");
} finally {
Files.deleteIfExists(report);
}
}
}
Choose a new report name
The example owns a temporary report. The second create sees that existing entry and leaves its contents alone.
Keep yesterday's shift total intact
An accountant has already written yesterday's total under a known filename. A second export uses exclusive creation, and the accountant checks that the first total survived the collision.
import java.nio.file.Files;
import java.nio.file.StandardOpenOption;
import java.nio.file.FileAlreadyExistsException;
class Main {
public static void main(String[] args) throws Exception {
var report = Files.createTempFile("total-", ".txt");
try {
Files.writeString(report, "Total 17");
try {
Files.writeString(report, "Total 9", StandardOpenOption.CREATE_NEW);
} catch (FileAlreadyExistsException taken) {
System.out.println(Files.readString(report));
}
} finally {
Files.deleteIfExists(report);
}
}
}
Total 17
CREATE_NEW refuses an existing path before writing any replacement content.
Issue the first parcel claim
The counter opens a new workspace for today’s pickup. Create the claim file exclusively so that an existing claim stays intact.
Code and output in Java
import java.util.*;
import java.io.*;
import java.nio.file.*;
import java.util.concurrent.*;
class Main {
public static void main(String[] args) throws Exception {
Path dir=Files.createTempDirectory("lesson-");
Path file=dir.resolve("record.txt");
try {
Files.createFile(file);
System.out.println("Claim created");
} catch (FileAlreadyExistsException e) {
System.out.println("Keep earlier claim");
} finally {
Files.deleteIfExists(file);
Files.deleteIfExists(dir);
}
}
}
Claim created
What to watch for
The specific exception is optional for some providers. Other I/O failures should propagate to the caller.