How to delete a directory in java

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

how to delete a directory in java

How to delete a folder in java using recursion

In java deleting a directory with files is not possible using java file delete() method of java.io.File class.

Also read – how to create a file in java

Java file delete() method deletes files of empty folder in java. delete() method returns true if files get deleted else return false.

File delete() method returns false by not deleting files inside a non-empty directory.

So to delete directory first we need to delete its sub-directories and files. We do not have method to delete directory with files.

In this post we are going to learn how to delete a non-empty directory/folder recursively,

import java.io.File;
import java.io.IOException;

public class DeleteDirectoryDemo 
{
   private static final String SRC_DIRECTORY = "D:\java-demo";

   public static void main(String[] args) 
   {
      File dir = new File(SRC_DIRECTORY);
      // make sure directory exists
      if(!dir.exists())
      {
         System.out.println("Directory does not exist.");
         System.exit(0);
      }
      else
      {
         try
         {
            directoryDelete(dir);
         }
         catch(IOException ex)
         {
            ex.printStackTrace();
            System.exit(0);
         }
      }
      System.out.println("Delete completed");
   }

   public static void directoryDelete(File file) throws IOException
   {
      if(file.isDirectory())
      {
         // if directory is empty, delete it
         if(file.list().length == 0)
         {   
            file.delete();
            System.out.println("Directory deleted : " + file.getAbsolutePath());
         }
         else
         {   
            // listing directory contents
            String files[] = file.list();
            for(String temp : files) 
            {
               File fileDelete = new File(file, temp);
               // directory recursive delete
               directoryDelete(fileDelete);
            }
            // checking directory again, if empty delete it
            if(file.list().length == 0)
            {
               file.delete();
               System.out.println("Directory is deleted : " + file.getAbsolutePath());
            }
         }
      }
      else
      {
         // if file found, delete it
         file.delete();
         System.out.println("File is deleted : " + file.getAbsolutePath());
      } 
   }
}



Also read – how to create directory in java