Java java.nio.file.Files deleteIfExists() Method

Java File Java java.nio.file.Files


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 deleted
  • false: if the file does not exist

Exceptions Thrown

  • IOException: if an I/O error occurs
  • SecurityException: if a security manager exists and denies delete access

Usage Scenarios

deleteIfExists()The method is particularly suitable for the following scenarios:

  1. Need to safely delete a file regardless of whether it exists
  2. Do not want an exception to be thrown because the file does not exist
  3. 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());
        }
    }
}

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());
}

Notes

  1. Directory deletion restriction: Only empty directories can be deleted; if the directory is not empty, it will throwDirectoryNotEmptyException
  2. Symbolic links: When deleting a symbolic link, only the link itself is deleted, and the target file is not affected
  3. File locking: If the file is locked by another process, the delete operation may fail
  4. 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

  1. Always check the return value to know whether the operation succeeded
  2. Properly handle the possible IOException
  3. For directory deletion, first ensure the directory is empty
  4. 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
}

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 File Java java.nio.file.Files

Other Extensions