How to delete a directory in java

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

How to delete a directory in java

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

File delete() method returns true if and only if the file or directory is successfully deleted; false otherwise.

Also read – how to create a file in java

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 – how to create directory in java


recursive java 8

In the below example we are using Files.walk(path) method to recursively delete specified directory and all its sub-directories.

Files.walk() method returns a Stream that is lazily populated with Path by walking the file tree rooted at a given starting file.

The file tree is traversed depth-first, the elements in the stream are Path objects that are obtained as if by resolving the relative path against start.

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Comparator;
public class Java8DeleteDirectory
{
   public static void main(String[] args)
   {
      Path directory = Paths.get("B:\\New folder");
      Files.walk(directory)
      .sorted(Comparator.reverseOrder())
      .forEach(path -> {
          try 
          {
             System.out.println("Deleting directory: " + path);
             Files.delete(path);
          } 
          catch(IOException ex) 
          {
             ex.printStackTrace();
          }
       });     
   }
}