Java delete directory

Hi everyone!! Welcome to flower brackets blog. In this post you are going to learn java delete directory.

java delete directory

In java, to delete a directory, compiler checks delete() method of File class. In order to delete a directory, directory must be empty.

Also read – create directory java program

We have to recursively delete directory. Because we need to delete its sub-directories. Now let’s see java program,

import java.io.*;

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

   public static void main(String[] args)
   {
      File directory = new File(SRC_FOLDER);

      // checking directory
      if(!directory.exists())
      {
         System.out.println("Directory doesn't exist!!!");
         System.exit(0);
      }
      else
      {
         try
         {  
            deleteDirectory(directory);
         }
         catch(IOException e)
         {
            e.printStackTrace();
            System.exit(0);
         }
      }
      System.out.println("deleted");
   }

   public static void deleteDirectory(File fl) throws IOException
   {
      if(fl.isDirectory())
      {
         // here directory is empty
         if(fl.list().length == 0)
         { 
            // deleted
            fl.delete();
            System.out.println("Directory deleted : " + fl.getAbsolutePath());
         }
         else
         { 
            // listing directory contents
            String files[] = fl.list();

            for(String temp : files) 
            {
               // file structure constructor
               File fileDelete = new File(fl, temp);
               // deleting recursively
               deleteDirectory(fileDelete);
            }

            // checking the directory
            if(fl.list().length == 0)
            {
               // deleting
               fl.delete();
               System.out.println("Directory deleted : " + fl.getAbsolutePath());
            }
         }
      }
      else
      {
         // deleting file
         fl.delete();
         System.out.println("File deleted : " + fl.getAbsolutePath());
      }
   }
}

Output:

File deleted : D:\\project-demo\home.html

File deleted : D:\\project-demo\about.html

Directory deleted : D:\\project-demo\projects

File deleted : D:\\project-demo\styles.php

File deleted : D:\\project-demo\contact.html

Directory deleted : D:\\project-demo\js\hover\css

Directory deleted : D:\\project-demo\js\mousehover

File deleted : D:\\project-demo\js\navbar.css

Directory deleted : D:\\project-demo

Related Posts