Delete Directories Recursively in Java

Delete directories recursively in Java

You should check out Apache's commons-io. It has a FileUtils class that will do what you want.

FileUtils.deleteDirectory(new File("directory"));

Java.nio: most concise recursive directory delete

You can combine NIO 2 and the Stream API.

Path rootPath = Paths.get("/data/to-delete");
// before you copy and paste the snippet
// - read the post till the end
// - read the javadoc to understand what the code will do
//
// a) to follow softlinks (removes the linked file too) use
// Files.walk(rootPath, FileVisitOption.FOLLOW_LINKS)
//
// b) to not follow softlinks (removes only the softlink) use
// the snippet below
try (Stream<Path> walk = Files.walk(rootPath)) {
walk.sorted(Comparator.reverseOrder())
.map(Path::toFile)
.peek(System.out::println)
.forEach(File::delete);
}
  • Files.walk - return all files/directories below rootPath including
  • .sorted - sort the list in reverse order, so the directory itself comes after the including subdirectories and files
  • .map - map the Path to File
  • .peek - is there only to show which entry is processed
  • .forEach - calls the .delete() method on every File object

EDIT As first mentioned by @Seby and now cited by @John Dough the Files.walk() should be used in a try-with-resource construct. Thanks to both.

From Files.walk javadoc

If timely disposal of file system resources is required, the try-with-resources construct should be used to ensure that the stream's close method is invoked after the stream operations are completed.

EDIT

Here are some figures.

The directory /data/to-delete contained the unpacked rt.jar of jdk1.8.0_73 and a recent build of activemq.

files: 36,427
dirs : 4,143
size : 514 MB

Times in milliseconds

                    int. SSD     ext. USB3
NIO + Stream API 1,126 11,943
FileVisitor 1,362 13,561

Both version were executed without printing file names. The most limiting factor is the drive. Not the implementation.

EDIT

Some addtional information about tthe option FileVisitOption.FOLLOW_LINKS.

Assume following file and directory structure

/data/dont-delete/bar
/data/to-delete/foo
/data/to-delete/dont-delete -> ../dont-delete

Using

Files.walk(rootPath, FileVisitOption.FOLLOW_LINKS)

will follow symlinks and the file /tmp/dont_delete/bar would be deleted as well.

Using

Files.walk(rootPath)

will not follow symlinks and the file /tmp/dont_delete/bar would not be deleted.

NOTE: Never use code as copy and paste without understanding what it does.

How to delete a folder with files using Java

Java isn't able to delete folders with data in it. You have to delete all files before deleting the folder.

Use something like:

String[]entries = index.list();
for(String s: entries){
File currentFile = new File(index.getPath(),s);
currentFile.delete();
}

Then you should be able to delete the folder by using index.delete()
Untested!

Java - Deleting files and folder of parent path recursively

You can use the ""new"" Java File API with Stream API:

 Path dirPath = Paths.get( "./yourDirectory" );
Files.walk( dirPath )
.map( Path::toFile )
.sorted( Comparator.comparing( File::isDirectory ) )
.forEach( File::delete );

Note that the call to sorted() method is here to delete all files before directories.

About one statement, and without any third party library ;)

Java 8 - Recursive delete of folders according to predicate

Files.walk will already stream a root path recursively depth first. FileUtils from apache commons has a deleteDirectory which removes directories recursively, making the code also quite clean.

So something like below should work

        Files.walk(rootPath)
.filter(Files::isDirectory).
.filter(TrashPredicate::isTrashFolder)
.forEach(FileUtils::deleteDirectory);

How to delete a folder containing other folders in Java?

To delete folder having files , no need of loops or recursive search. You can directly use:

FileUtils.deleteDirectory(<File object of directory>);

This function will delete the folder and all files in it

Delete directory recursively in Scala

With pure scala + java way

import scala.reflect.io.Directory
import java.io.File

val directory = new Directory(new File("/sampleDirectory"))
directory.deleteRecursively()

deleteRecursively() Returns false on failure



Related Topics



Leave a reply



Submit