How to delete a directory in java(Recursively)

Let’s learn how to delete a directory in java(Recursively).

How to delete a directory in java(Recursively)

In java to delete a directory use delete() method of java.io.File class. delete() method deletes file or directory denoted by this abstract pathname.

If this pathname denotes a directory, then the directory must be empty in order to be deleted.

how to delete a directory in java

delete() method returns true if and only if the file or directory is successfully deleted; false otherwise. Let’s learn to delete a directory using recursion or recursively.

import java.io.File;
public class DeleteDirectoryRecursively
{
   public static void main(String[] args)
   {
      String strFolder = "B:\New folder";
      //delete folder recursively
      deleteRecursive(new File(strFolder));
   }
   public static void deleteRecursive(File fl)
   {
      if(!fl.exists())
         return;
      // if directory call recursively
      if(fl.isDirectory())
      {
         for(File file : fl.listFiles())
         {
            // recursive call
            deleteRecursive(file);
         }
      }
      // delete files and empty directory
      fl.delete();
      System.out.println("Deleted file/directory: " + fl.getAbsolutePath());
   }
}


Output:

Deleted file/directory: B:\New folder\123.txt Deleted file/directory: B:\New folder\abc.txt Deleted file/directory: B:\New folder\New folder2\456.txt

Deleted file/directory: B:\New folder\New folder2\New folder3\bmw.txt

Deleted file/directory: B:\New folder\New folder2\New folder3\mno.txt

Deleted file/directory: B:\New folder\New folder2\New folder3\tvs.txt


Also read – java overview