Java Files delete()

📘 Premium Read: Access my best content on Medium member-only articles — deep dives into Java, Spring Boot, Microservices, backend architecture, interview preparation, career advice, and industry-standard best practices.

🎓 Top 15 Udemy Courses (80-90% Discount): My Udemy Courses - Ramesh Fadatare — All my Udemy courses are real-time and project oriented courses.

▶️ Subscribe to My YouTube Channel (176K+ subscribers): Java Guides on YouTube

▶️ For AI, ChatGPT, Web, Tech, and Generative AI, subscribe to another channel: Ramesh Fadatare on YouTube

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

Spring Boot 3 Paid Course Published for Free
on my Java Guides YouTube Channel

Subscribe to my YouTube Channel (165K+ subscribers):
Java Guides Channel

Top 10 My Udemy Courses with Huge Discount:
Udemy Courses - Ramesh Fadatare