Java Program to Delete Empty and Non-empty Directory

Java Program to Delete Empty and Non-empty Directory

What are Directories?

In Java, a directory is a file path that points to a location on a file system where multiple files and other directories can be stored. It is used to organize and group files and folders in a hierarchical structure. A directory can be created, deleted, and navigated using the java.io.File class, which provides methods for working with directories in a platform-independent way.

In this Article, we will write a program to Delete Empty and Non-empty Directory.

Directories in Java :

In Java, directories are represented by the java.io.File class, which provides methods for working with directories in a platform-independent way. The File class can be used to create, delete, and navigate directories, as well as perform other operations such as checking if a file or directory exists, or getting information about a file or directory.

Some of the commonly used methods of the File class for working with directories include:
  • File.mkdir(): creates a new directory
  • File.mkdirs(): creates a new directory, including any necessary but nonexistent parent directories
  • File.list(): returns an array of strings naming the files and directories in the directory
  • File.listFiles(): returns an array of File objects for the files and directories in the directory
  • File.isDirectory(): returns true if the file is a directory, false otherwise
  • File.delete(): deletes the directory and all the files and subdirectories inside it

It is important to note that the File class only provides methods for working with directories on the local file system. To work with directories on a remote file system or network, such as a network file share or FTP server, you will need to use a different library or framework.

Program to delete an empty directory :

Run
import java.io.File;

public class Main{
    public static void main(String[] args) {
        
        // Provide the path of the directory to be deleted
        String directoryPath = "path/to/directory";
        
        File directory = new File(directoryPath);
        
        // Check if the directory exists
        if (directory.exists()) {
            
            // Check if the directory is empty
            if (directory.list().length == 0) {
                
                // Delete the empty directory
                directory.delete();
                System.out.println("Directory deleted successfully");
            } else {
                System.out.println("Directory is not empty");
            }
        } else {
            System.out.println("Directory does not exist");
        }
    }
}

Explanation:

This program first uses the File class to create a File object for the specified directory path. It then checks if the directory exists using the exists() method, and if it does, it checks if the directory is empty using the list().length method. If the directory is empty, it is deleted using the delete() method and a message is printed indicating that the directory was deleted successfully. If the directory is not empty or does not exist, a message is printed indicating that the directory is not empty or does not exist.

Please note that, if you want to delete a non-empty directory, you can use the delete() method of the File class but it will only delete the empty sub-directories, and not the files within the directory. To delete a non-empty directory, you can use the following approach:

  • Create a method that deletes the files within the directory
  • Call that method before calling the delete method
  • Then call the delete method of the File class on the directory.

Program to Delete a non-empty directory :

Run
import java.io.File;

public class Main{
    public static void main(String[] args) {
        // Directory path to be deleted
        String directoryPath = "path/to/directory";
        File directory = new File(directoryPath);

        // Call the deleteDirectory method
        deleteDirectory(directory);
    }

    public static void deleteDirectory(File directory) {
        // Get all the files and directories in the directory
        File[] files = directory.listFiles();

        if(files != null) {
            // Iterate through all the files and directories
            for(File file : files) {
                // If the file is a directory, call the deleteDirectory method recursively
                if(file.isDirectory()) {
                    deleteDirectory(file);
                } else {
                    // If the file is a file, delete it
                    file.delete();
                }
            }
        }
        // After deleting all the files and directories, delete the directory itself
        directory.delete();
    }
}

Explanation:

In this example, the program takes a directory path as input and creates a File object for that directory. Then, it calls the deleteDirectory method, which recursively deletes all the files and directories within the given directory. Finally, it deletes the directory itself.

Prime Course Trailer

Related Banners

Get PrepInsta Prime & get Access to all 200+ courses offered by PrepInsta in One Subscription

Get over 200+ course One Subscription

Courses like AI/ML, Cloud Computing, Ethical Hacking, C, C++, Java, Python, DSA (All Languages), Competitive Coding (All Languages), TCS, Infosys, Wipro, Amazon, DBMS, SQL and others

Checkout list of all the video courses in PrepInsta Prime Subscription

Checkout list of all the video courses in PrepInsta Prime Subscription