how to force delete directory in java code example

Example 1: How to delete a directory in java

// delete a directory in java 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());
   }
}

Example 2: java delete directory

boolean deleteDirectory(File directoryToBeDeleted) {
    File[] allContents = directoryToBeDeleted.listFiles();
    if (allContents != null) {
        for (File file : allContents) {
            deleteDirectory(file);
        }
    }
    return directoryToBeDeleted.delete();
}

Tags:

Java Example