Java Files delete()

In this guide, you will learn about the Files.delete() method in Java programming and how to use it with an example.

1. Files delete() Method Overview

Definition:

The Files.delete() method is a utility method in Java's NIO (New I/O) package designed to delete a file or directory. If the file is a directory, it must be empty to be deleted.

Syntax:

static void delete(Path path) throws IOException

Parameters:

- path: the path to the file or directory to delete.

Key Points:

- The method throws an IOException if an I/O error occurs or if the file does not exist.

- If the given path denotes a directory, then the directory must be empty in order to be deleted.

- Unlike the File.delete() method from Java's traditional I/O, Files.delete() provides more detailed exception messages which can be useful for debugging.

- If the file or directory doesn't exist, a NoSuchFileException is thrown.

2. Files delete() Method Example

import java.io.IOException;
import java.nio.file.DirectoryNotEmptyException;
import java.nio.file.Files;
import java.nio.file.NoSuchFileException;
import java.nio.file.Path;
import java.nio.file.Paths;

public class FilesDeleteExample {
    public static void main(String[] args) {
        Path filePath = Paths.get("sample.txt");

        try {
            Files.delete(filePath);
            System.out.println("File deleted successfully!");
        } catch (NoSuchFileException e) {
            System.out.println("File does not exist.");
        } catch (DirectoryNotEmptyException e) {
            System.out.println("Directory is not empty.");
        } catch (IOException e) {
            System.out.println("An I/O error occurred: " + e.getMessage());
        }
    }
}

Output:

File deleted successfully!

Explanation:

In the example, we attempt to delete a file named sample.txt. If the operation succeeds, a success message is printed. If the file doesn't exist, a NoSuchFileException is thrown. 

In case the provided path denotes a directory that is not empty, a DirectoryNotEmptyException is thrown. Other I/O errors are also caught and handled.

Comments