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 directory in java

In java to delete a directory use delete() method of java.io.File class. delete() method deletes the 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.

Also read – how to create a file in java

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

Here’s a program to delete a directory,

NOTE: in the below example there should be some files in order to delete a directory.

import java.io.File;

public class DeleteDirectoryDemo
{
   public static void main(String[] args)
   {
      File directory = new File("B:\New folder");
      if(directory.isDirectory() == false)
      {
         System.out.println("This is not a directory.unable to delete file.");
         return;
      }
      File[] fileList = directory.listFiles();
      for(File fl : fileList)
      {
         System.out.println("Deleting file: " + fl.getName());
         fl.delete();
      }
      // directory is empty, delete
      System.out.println("Is Directory deleted: " + directory.delete());
   }
}


Output:

Deleting file: abc.txt
Deleting file: xyz.txt
Is Directory deleted: true

This is not a directory. unable to delete file.


Also read – how to create directory in java


java 8 delete non empty

To delete a non empty directory in java 8 use Files.walk() method of java.nio package.

Files.walk() method return 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.

In the below example we are also using File.delete() method to recursively delete given directory along with its sub-directories.

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)
   {
      File fl = new File("B:\New folder");
      try
      {
         directoryDelete(fl.toPath());
         System.out.println("Directory deleted successfully.");
      }
      catch(IOException ex)
      {
         ex.printStackTrace();
      }
   }

   public static void directoryDelete(Path dir) throws IOException
   {
      Files.walk(dir).sorted(Comparator.reverseOrder())
.map(Path::toFile).forEach(File::delete);
   }
}


Output:

Directory deleted successfully.


delete all files with extension

To delete all files with extension in directory implement FilenameFilter interface.

In FilenameFilter interface instances of classes that implement this interface are used to filter filenames.

These instances are used to filter directory listings in the list method of class File, and by the Abstract Window Toolkit’s file dialog component.

import java.io.File;
import java.io.FilenameFilter;

public class DeleteFilesWithExtension
{
   private static final String DIRECTORY = "B:\New folder";
   private static final String TEXTEXTENSION = ".txt";

   public void deleteFile(String strDirectory, String strExtension)
   {
      GenericExtFilter gef = new GenericExtFilter(strExtension);
      File fl = new File(strDirectory);
      // list file name with .txt extension
      String[] strList = fl.list(gef);
      if(strList.length == 0)
         return;
      File flDelete;
      for(String str : strList)
      {
         String strTemp = new StringBuffer(DIRECTORY).append(File.separator).append(str).toString();
         flDelete = new File(strTemp);
         boolean boolDeleted = flDelete.delete();
         System.out.println("File name: " + strTemp + " is deleted: " + boolDeleted);
      }
   }

   public static void main(String[] args)
   {
      new DeleteFilesWithExtension().deleteFile(DIRECTORY, TEXTEXTENSION);
   }

   public class GenericExtFilter implements FilenameFilter
   {
      private String strExt;
      public GenericExtFilter(String ext)
      {
         this.strExt = ext;
      }
      public boolean accept(File dir, String name)
      {
         return (name.endsWith(strExt));
      }
   }
}


Output:

File name: B:\New folder\123.txt is deleted: true
File name: B:\New folder\abc.txt is deleted: true
File name: B:\New folder\mno.txt is deleted: true
File name: B:\New folder\pqr.txt is deleted: true
File name: B:\New folder\xyz.txt is deleted: true


delete directory if exists

To delete directory if exists use deleteIfExists() method of java.nio.file.Files package.

deleteIfExists() method returns true if the file was deleted by this method; false if the file could not be deleted because it did not exist.

Let’s see program on delete directory if exists,

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

public class DirectoryIfExists
{
   public static void main(String[] args)
   {
      Path path = Paths.get("B:\New folder\123.txt");
      try
      {
         Files.deleteIfExists(path);
      }
      catch(IOException ex)
      {
         ex.printStackTrace();
      }
   }
}



delete a directory using recursion or recursively

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

public class DeleteFileRecursively
{
   private static final String SOURCEFOLDER = "B:\New folder";

   public static void main(String[] args) throws IOException
   {
      File dir = new File(SOURCEFOLDER);
      // check if directory exists
      if(!dir.exists())
      {
         System.out.println("Directory does not exist.");
         System.exit(0);
      }
      else
      {
         try
         {
            deleteRecursive(dir);
         }
         catch(IOException ex)
         {
            ex.printStackTrace();
            System.exit(0);
         }
      }
      System.out.println("Recursive directory delete completed.");
   }

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


Output:

File is deleted: B:\New folder\123.txt
File is deleted: B:\New folder\abc.txt
File is deleted: B:\New folder\New folder2\456.txt
File is deleted: B:\New folder\New folder2\New folder3\bmw.txt
File is deleted: B:\New folder\New folder2\New folder3\mno.txt
File is deleted: B:\New folder\New folder2\New folder3\tvs.txt
Directory is deleted: B:\New folder\New folder2\New folder3
File is deleted: B:\New folder\New folder2\pqr.txt
Directory is deleted: B:\New folder\New folder2
File is deleted: B:\New folder\xyz.txt
Directory is deleted: B:\New folder
Recursive directory delete completed.