Java : FileAlreadyExistsException with Examples
FileAlreadyExistsException (Java SE 22 & JDK 22) in Java with Examples.
You will find code samples for most of the FileAlreadyExistsException methods.
Summary
final var file = Path.of("R:", "java-work", "aaa.txt");
System.out.println(file); // R:\java-work\aaa.txt
Files.createFile(file);
System.out.println(Files.exists(file)); // true
try {
System.out.println("-- createFile --");
Files.createFile(file);
} catch (FileAlreadyExistsException e) {
System.out.println(e);
}
// Result
// ↓
//-- createFile --
//java.nio.file.FileAlreadyExistsException: R:\java-work\aaa.txt
final var src = Path.of("R:", "java-work", "aaa.txt");
final var dst = Path.of("R:", "java-work", "bbb.txt");
System.out.println(src); // R:\java-work\aaa.txt
System.out.println(dst); // R:\java-work\bbb.txt
Files.createFile(src);
Files.createFile(dst);
System.out.println(Files.exists(src)); // true
System.out.println(Files.exists(dst)); // true
try {
System.out.println("-- copy --");
Files.copy(src, dst);
} catch (FileAlreadyExistsException e) {
System.out.println(e);
}
// Result
// ↓
//-- copy --
//java.nio.file.FileAlreadyExistsException: R:\java-work\bbb.txt
Constructors
FileAlreadyExistsException (String file)
final var e = new FileAlreadyExistsException("aaa.txt");
System.out.println(e); // java.nio.file.FileAlreadyExistsException: aaa.txt
System.out.println(e.getFile()); // aaa.txt
FileAlreadyExistsException (String file, String other, String reason)
final var e = new FileAlreadyExistsException("aaa.txt", "bbb.txt", "Reason!");
// java.nio.file.FileAlreadyExistsException: aaa.txt -> bbb.txt: Reason!
System.out.println(e);
System.out.println(e.getFile()); // aaa.txt
System.out.println(e.getOtherFile()); // bbb.txt
System.out.println(e.getReason()); // Reason!
System.out.println(e.getMessage()); // aaa.txt -> bbb.txt: Reason!
Methods declared in FileSystemException
getFile, getMessage, getOtherFile, getReason
Please see the link below.
Methods declared in Throwable
addSuppressed, fillInStackTrace, getCause, getLocalizedMessage, getStackTrace, getSuppressed, initCause, printStackTrace, printStackTrace, printStackTrace, setStackTrace, toString
Please see the link below.