Java java.nio.file.Files deleteIfExists() Method
java.nio.file.Files.deleteIfExists()is a utility method in the Java NIO (New Input/Output) package, used to delete files or empty directories in the file system. Unlike thedelete()method,deleteIfExists()it does not throw an exception when the file does not exist, but instead returnsfalse。
Method Syntax
public static boolean deleteIfExists(Path path) throws IOException
Parameter Description
path: the path of the file or directory to be deleted (Pathobject)
Return Value
true: if the file exists and is successfully deletedfalse: if the file does not exist
Exceptions Thrown
IOException: if an I/O error occursSecurityException: if a security manager exists and denies delete access
Usage Scenarios
deleteIfExists()The method is particularly suitable for the following scenarios:
- Need to safely delete a file regardless of whether it exists
- Do not want an exception to be thrown because the file does not exist
- Need to know whether the file was actually deleted (via the return value)
Example Code
Basic Usage
Example
import java.nio.file.*;
public class DeleteFileExample {
public static void main(String[] args) {
Path path = Paths.get("example.txt");
try {
boolean deleted = Files.deleteIfExists(path);
if (deleted) {
System.out.println("File deleted successfully");
} else {
System.out.println("File does not exist, no need to delete");
}
} catch (IOException e) {
System.err.println("Error deleting file: " + e.getMessage());
}
}
}
public class DeleteFileExample {
public static void main(String[] args) {
Path path = Paths.get("example.txt");
try {
boolean deleted = Files.deleteIfExists(path);
if (deleted) {
System.out.println("File deleted successfully");
} else {
System.out.println("File does not exist, no need to delete");
}
} catch (IOException e) {
System.err.println("Error deleting file: " + e.getMessage());
}
}
}
Delete directory (must be an empty directory)
Example
Path dirPath = Paths.get("empty_directory");
try {
boolean deleted = Files.deleteIfExists(dirPath);
// Handle the result...
} catch (DirectoryNotEmptyException e) {
System.err.println("Directory is not empty, cannot delete");
} catch (IOException e) {
System.err.println("Other I/O error: " + e.getMessage());
}
try {
boolean deleted = Files.deleteIfExists(dirPath);
// Handle the result...
} catch (DirectoryNotEmptyException e) {
System.err.println("Directory is not empty, cannot delete");
} catch (IOException e) {
System.err.println("Other I/O error: " + e.getMessage());
}
Notes
- Directory deletion restriction: Only empty directories can be deleted; if the directory is not empty, it will throw
DirectoryNotEmptyException - Symbolic links: When deleting a symbolic link, only the link itself is deleted, and the target file is not affected
- File locking: If the file is locked by another process, the delete operation may fail
- Permission issues: Sufficient permissions are required to delete the file
Comparison with Other Methods
| Method | Behavior when file does not exist | Return value |
|---|---|---|
Files.deleteIfExists() |
Returns false | boolean |
Files.delete() |
Throws NoSuchFileException | void |
File.delete()(Traditional IO) |
Returns false | boolean |
Best Practices
- Always check the return value to know whether the operation succeeded
- Properly handle the possible IOException
- For directory deletion, first ensure the directory is empty
- Consider using try-with-resources to handle related resources
Example
try {
if (Files.deleteIfExists(path)) {
// File exists and was deleted
} else {
// File does not exist
}
} catch (IOException e) {
// Handle exception
}
if (Files.deleteIfExists(path)) {
// File exists and was deleted
} else {
// File does not exist
}
} catch (IOException e) {
// Handle exception
}
Summary
Files.deleteIfExists()It provides a safe, convenient way to delete files, especially suitable for scenarios where you are not sure whether the file exists but still need to delete it. Compared with the traditionalFile.delete()method, it provides richer exception information and more flexible NIO path handling capabilities.
Java java.nio.file.Files