Java Delete Directory Recursively

If you are working on a Java swing application/ desktop application then it may be required sometimes that you need to delete a directory from the file system with all inner directories and files inside it.

Use of the following examples to delete a directory (including subdirectories) and all the files in it.

1. FileUtils.deleteDirectory() – Apache Commons IO

Apache commons IO module has class FileUtils. It’s deleteDirectory( file ) method can be used delete a directory along with all sub-directories and files inside it.

Example 1: Delete a directory, sub-directories and all files in it

import org.apache.commons.io.FileUtils;
import java.io.File;

public class DeleteDirectoryCommonsIO 
{
	public static void main(String[] args) 
	{
		File file = FileUtils.getFile("c:/temp/innerDir");

		FileUtils.deleteDirectory( file );
	}
}

2. Files.delete() – Java NIO

Another approach is to use Files.walkFileTree() to iterate over all the sub-directories and files in a given directory and delete them one by one.

It works in two steps recursively:

  1. It first delete all files in a directory; then
  2. It delete the directory itself

Example 2: Deleting a directory recursively

This Java example uses Files.walkFileTree() method and SimpleFileVisitor to perform delete operation.

import java.io.IOException;
import java.nio.file.FileVisitResult;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.SimpleFileVisitor;
import java.nio.file.attribute.BasicFileAttributes;

public class DeleteDirectoryNIO 
{
	public static void main(String[] args) 
	{
		Path dir = Paths.get("c:/temp/innerDir");
		try 
		{
			Files.walkFileTree(dir, new SimpleFileVisitor<Path>() 
			{
			      @Override
			      public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) 
			    		  throws IOException 
			      {
			          System.out.println("Deleting file: " + file);
			          Files.delete(file);
			          return FileVisitResult.CONTINUE;
			      }
			 
			      @Override
			      public FileVisitResult postVisitDirectory(Path dir,
			              IOException exc) throws IOException 
			      {
			          System.out.println("Deleting dir: " + dir);
			          if (exc == null) {
			              Files.delete(dir);
			              return FileVisitResult.CONTINUE;
			          } else {
			              throw exc;
			          }
				   }
 
				});
		} 
		catch (IOException e) 
		{
		  e.printStackTrace();
		}
	}
}

3. Delete directory in Java 8

Since Java 8, we can combine the Java NIO operations with java streams and above approach becomes so much clean.

Example 3: Deleting a directory recursively in Java 8

public class DeleteDirectoryNIOWithStream 
{
	public static void main(String[] args) 
	{
		Path dir = Paths.get("c:/temp/innerDir");

		Files.walk(dir)
      		.sorted(Comparator.reverseOrder())
      		.map(Path::toFile)
      		.forEach(File::delete);
	}
}

Here, Files.walk() returns a Stream of paths denoting the contents of directories (i.e. files) before directories itself. Thereafter it maps Path to File and deletes each file. Now you use delete() method to delete the file itself.

Use the above code examples handy whenever you want to delete a directory with all files inside it.

Happy Learning !!

Was this post helpful?

Join 7000+ Awesome Developers

Get the latest updates from industry, awesome resources, blog updates and much more.

* We do not spam !!

2 thoughts on “Java Delete Directory Recursively”

    • “No exceptions are thrown when a file or directory cannot be deleted”. This may not be the desired behavior in many cases. Otherwise it is also doing the same as above code i.e. first delete all containing files and then delete the directory itself.

      public static boolean deleteQuietly(final File file) {
      	if (file == null) {
      		return false;
      	}
      	try {
      		if (file.isDirectory()) {
      			cleanDirectory(file);
      		}
      	} catch (final Exception ignored) {
      	}
      
      	try {
      		return file.delete();
      	} catch (final Exception ignored) {
      		return false;
      	}
      }
      Reply

Leave a Comment

HowToDoInJava

A blog about Java and related technologies, the best practices, algorithms, and interview questions.