Delete a Directory Recursively in Java

Learn to use classes from Java IO, New IO and Commons IO to delete a directory including all the subdirectories and files in it.

1. Using FileUtils.deleteDirectory() from Apache Commons IO

Include Commons IO module in the project using Maven dependencies.

<dependency>
    <groupId>commons-io</groupId>
    <artifactId>commons-io</artifactId>
    <version>2.11.0</version>
</dependency>

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

This method throws IOException in case deletion is unsuccessful for any reason.

File file = FileUtils.getFile("c:/temp/innerDir");

FileUtils.deleteDirectory( file );

Use another method deleteQuitly(dir) to delete quietly. This method never throws an exception. It returns true if the directory was deleted, otherwise false.

File file = FileUtils.getFile("c:/temp/innerDir");

boolean isDeleted = FileUtils.deleteQuietly( file );

2. Using Files.delete() from Java NIO

Another approach in Java documentation 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 deletes all files in a directory; then
  2. It deletes the directory itself

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&lt;Path&gt;()
			{
			      @Override
			      public FileVisitResult visitFile(Path file, BasicFileAttributes attrs)
			    		  throws IOException
			      {
			          System.out.println("Deleting the file: " + file);
			          Files.delete(file);
			          return FileVisitResult.CONTINUE;
			      }

			      @Override
			      public FileVisitResult postVisitDirectory(Path dir,
			              IOException exc) throws IOException
			      {
			          System.out.println("Deleting the dir: " + dir);
			          if (exc == null) {
			              Files.delete(dir);
			              return FileVisitResult.CONTINUE;
			          } else {
			              throw exc;
			          }
				   }

				});
		}
		catch (IOException e)
		{
		  e.printStackTrace();
		}
	}
}

3. Deleting Directory in Java 8

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

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 themselves. 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 !!

Source Code on Github

Comments

Subscribe
Notify of
guest
2 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments

About Us

HowToDoInJava provides tutorials and how-to guides on Java and related technologies.

It also shares the best practices, algorithms & solutions and frequently asked interview questions.

Our Blogs

REST API Tutorial

Dark Mode

Dark Mode