Learn Java by Example: Java Program to Delete Empty and Non-empty Directory

Java Program to Delete Empty and Non-empty Directory

In this example, we will learn to delete an empty directory, a non-empty directory, and a directory with non-empty subdirectory in Java.

 


Example 1: Java Program to delete an empty directory


import java.io.File;

class Main{
  public static void main(String[] args){

    try {
      // create a new file object
      File directory = new File("Directory");

      // delete the directory
      boolean result = directory.delete();

      if(result) {
        System.out.println("Directory Deleted");
      }
      else {
        System.out.println("Directory not Found");
      }

    } catch (Exception e) {
      e.getStackTrace();
    }
  }
}

In the above example, we have used the delete() method of the File class to delete the directory named Directory.

Here, if the directory is present, then the message Directory Deleted is shown. Otherwise, Directory not Found is shown.


Example 2: Delete a non-empty directory

In Java, to delete a non-empty directory, we must first delete all the files present in the directory. Then, we can delete the directory.


import java.io.File;

class Main{
  public static void main(String[] args){

    try {
      // create a new file object
      File directory = new File("Directory");

      // list all the files in an array
      File[] files = directory.listFiles();

      // delete each file from the directory
      for(File file : files) {
        System.out.println(file + " deleted.");
        file.delete();
      }

      // delete the directory
      if(directory.delete()) {
        System.out.println("Directory Deleted");
      }
      else {
        System.out.println("Directory not Found");
      }

    } catch (Exception e) {
      e.getStackTrace();
    }
  }
}

In the above example, we have used the for-each loop to delete all the files present in the directory. Once, all files are deleted, we used the delete() method to delete the directory.


Example 3: Delete non-empty directory recursively


import java.io.File;

class Main{

  public static void deleteDirectory(File directory){

    // if the file is directory or not
    if(directory.isDirectory()) {
      File[] files = directory.listFiles();

      // if the directory contains any file
      if(files != null) {
        for(File file : files) {

          // recursive call if the subdirectory is non-empty
          deleteDirectory(file);
        }
      }
    }

    if(directory.delete()) {
      System.out.println(directory + " is deleted");
    }
    else {
      System.out.println("Directory not deleted");
    }
  }
  public static void main(String[] args){

    try {
      // create a new file object
      File directory = new File("Directory");

      Main.deleteDirectory(directory);

    } catch (Exception e) {
      e.getStackTrace();
    }
  }
}

Here, suppose we have a non-empty directory named Directory. The Directory contains 2 files named file1.txt and file2.txt and a non-empty subdirectory named Subdirectory. Again, the Subdirectory contains a file named file11.txt.

Now, when we run the program, we will get the following output.

Directoryfile1.txt is deleted
Directoryfile2.txt is deleted
DirectorySubdirectoryfile11.txt is deleted
DirectorySubdirectory is deleted
Directory is deleted

Here, first 2 files are deleted, then the recursive function delete the files inside the Subdirectory. Once, the Subdirectory is empty, it is deleted. And, finally the Directory is deleted.

 

 

Python Example for Beginners

Two Machine Learning Fields

There are two sides to machine learning:

  • Practical Machine Learning:This is about querying databases, cleaning data, writing scripts to transform data and gluing algorithm and libraries together and writing custom code to squeeze reliable answers from data to satisfy difficult and ill defined questions. It’s the mess of reality.
  • Theoretical Machine Learning: This is about math and abstraction and idealized scenarios and limits and beauty and informing what is possible. It is a whole lot neater and cleaner and removed from the mess of reality.

Data Science Resources: Data Science Recipes and Applied Machine Learning Recipes

Introduction to Applied Machine Learning & Data Science for Beginners, Business Analysts, Students, Researchers and Freelancers with Python & R Codes @ Western Australian Center for Applied Machine Learning & Data Science (WACAMLDS) !!!

Latest end-to-end Learn by Coding Recipes in Project-Based Learning:

Applied Statistics with R for Beginners and Business Professionals

Data Science and Machine Learning Projects in Python: Tabular Data Analytics

Data Science and Machine Learning Projects in R: Tabular Data Analytics

Python Machine Learning & Data Science Recipes: Learn by Coding

R Machine Learning & Data Science Recipes: Learn by Coding

Comparing Different Machine Learning Algorithms in Python for Classification (FREE)

Disclaimer: The information and code presented within this recipe/tutorial is only for educational and coaching purposes for beginners and developers. Anyone can practice and apply the recipe/tutorial presented here, but the reader is taking full responsibility for his/her actions. The author (content curator) of this recipe (code / program) has made every effort to ensure the accuracy of the information was correct at time of publication. The author (content curator) does not assume and hereby disclaims any liability to any party for any loss, damage, or disruption caused by errors or omissions, whether such errors or omissions result from accident, negligence, or any other cause. The information presented here could also be found in public knowledge domains.