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

Java File Java java.nio.file.Files


java.nio.file.Files.delete()is a static method provided in the Java NIO (New I/O) package, used to delete files or empty directories. This method belongs tojava.nio.filepackage, and is part of the file system operation API introduced in Java 7.

Method Syntax

public static void delete(Path path) throws IOException

Parameter Description

  • path: The path of the file or directory to delete, of typejava.nio.file.Path

Return Value

This method has no return value (void type)

Exceptions Thrown

  • NoSuchFileException: If the file does not exist
  • DirectoryNotEmptyException: If attempting to delete a non-empty directory
  • IOException: If an I/O error occurs
  • SecurityException: If there is no permission to delete the file

Method Features

Deletion Behavior

  • Can only delete files or empty directories
  • If the directory is not empty, it will throwDirectoryNotEmptyException
  • The deletion operation is atomic

Difference from File.delete()

Compared to the traditionaljava.io.File.delete()method,Files.delete()provides more detailed exception information, helping developers better handle deletion failures.


Usage Examples

Basic Usage

Example

import java.nio.file.*;

public class FileDeleteExample {
    public static void main(String[] args) {
        Path path = Paths.get("example.txt");
       
        try {
            Files.delete(path);
            System.out.println("File deleted successfully");
        } catch (NoSuchFileException e) {
            System.out.println("File does not exist: " + path);
        } catch (DirectoryNotEmptyException e) {
            System.out.println("Directory is not empty: " + path);
        } catch (IOException e) {
            System.out.println("Error occurred while deleting file: " + e.getMessage());
        }
    }
}

Deleting a Directory

Example

import java.nio.file.*;

public class DirectoryDeleteExample {
    public static void main(String[] args) {
        Path dirPath = Paths.get("empty_directory");
       
        try {
            Files.delete(dirPath);
            System.out.println("Directory deleted successfully");
        } catch (DirectoryNotEmptyException e) {
            System.out.println("Cannot delete non-empty directory: " + dirPath);
            System.out.println("Please delete the contents of the directory first");
        } catch (IOException e) {
            System.out.println("Error occurred while deleting directory: " + e.getMessage());
        }
    }
}

Best Practices

Check if the file exists before deletion

Example

Path path = Paths.get("file_to_delete.txt");
if (Files.exists(path)) {
    try {
        Files.delete(path);
    } catch (IOException e) {
        e.printStackTrace();
    }
}

Handling Symbolic Links

delete()The method deletes the symbolic link itself, not the target file pointed to by the link.

Example

Path linkPath = Paths.get("symbolic_link");
try {
    Files.delete(linkPath); // Only deletes the link, does not affect the target file
} catch (IOException e) {
    e.printStackTrace();
}

Using with deleteIfExists()

Java also providesFiles.deleteIfExists()method, which silently returns if the file does not exist instead of throwing an exception.

Example

Path path = Paths.get("maybe_existing_file.txt");
try {
    boolean deleted = Files.deleteIfExists(path);
    if (deleted) {
        System.out.println("File deleted");
    } else {
        System.out.println("File does not exist, no need to delete");
    }
} catch (IOException e) {
    e.printStackTrace();
}

Notes

  1. Permission issues: Ensure the program has permission to delete the target file
  2. File locking: If the file is locked by another process, deletion may fail
  3. Cross-platform behavior: Different operating systems may have different implementations of file deletion
  4. Atomicity: The deletion operation is atomic, but may not take effect immediately on some file systems
  5. Resource management: The deletion operation does not automatically close open file streams; you need to ensure the file is not in use

Summary

Files.delete()method is a powerful tool in Java NIO for deleting files or empty directories. Compared with the traditionalFile.delete(), it provides more detailed exception information, making error handling more precise. In actual development, it is recommended to combine withFiles.exists()or directly useFiles.deleteIfExists()to write more robust code.

Java File Java java.nio.file.Files

Other Extensions