Delete directory with all files java

Delete directory with all files java

Removing empty directory in Java is as simple as calling File.delete() (standard IO) or Files.delete() (NIO) method. However, if the folder is not empty (for example contains one or more files or subdirectories), these methods will refuse to remove it. In this post I want to present few ways to recursively remove the directory together with its contents.

Standard recursion (Java 6 and before)

The first method recursively removes files and directories from the directory tree starting from the leaves. Because it uses old I/O class File for operating on files and directories, this method can be used in any Java version.

void deleteDirectoryRecursionJava6(File file) throws IOException < if (file.isDirectory()) < File[] entries = file.listFiles(); if (entries != null) < for (File entry : entries) < deleteDirectoryRecursionJava6(entry); >> > if (!file.delete()) < throw new IOException("Failed to delete " + file); >>

Standard recursion using NIO (since Java 7)

Java 7 introduced improved API for I/O operations (also known as NIO). Once we decide to use it, the first method can be changed as follows:

void deleteDirectoryRecursion(Path path) throws IOException < if (Files.isDirectory(path, LinkOption.NOFOLLOW_LINKS)) < try (DirectoryStreamentries = Files.newDirectoryStream(path)) < for (Path entry : entries) < deleteDirectoryRecursion(entry); >> > Files.delete(path); >

Walk tree (since Java 7)

Additionally, Java 7 introduced new method Files.walkFileTree() which traverses directory tree in the file-system using visitor design pattern. This new method can be easily used to recursively delete directory:

void deleteDirectoryWalkTree(Path path) throws IOException < FileVisitor visitor = new SimpleFileVisitor() < @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException < Files.delete(file); return FileVisitResult.CONTINUE; >@Override public FileVisitResult visitFileFailed(Path file, IOException exc) throws IOException < Files.delete(file); return FileVisitResult.CONTINUE; >@Override public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException < if (exc != null) < throw exc; >Files.delete(dir); return FileVisitResult.CONTINUE; > >; Files.walkFileTree(path, visitor); >

Streams and NIO2 (since Java 8)

Since Java 8 we can use Files.walk() method which behaves like this according to the official documentation:

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.

The stream has to be sorted in reverse order first to prevent removal of non-empty directory. The final code looks like this:

Читайте также:  Классы методы интерфейсы java

void deleteDirectoryStream(Path path) throws IOException

However, this code has two drawbacks:

  • The stream is being sorted so all stream elements must be present in memory at the same time. This may significantly increase memory consumption for deep directory trees.
  • There is no error handling because the return value from File.delete() is ignored. This can be improved by using custom lambda inside forEach().

Apache Commons IO

Finally, there is a one-liner solution for the impatient. Just add Maven dependency:

and call this single method:

FileUtils.deleteDirectory(file);

Conclusion

All of above methods should do the job. Personally, I prefer the last one because it is the simplest to use. The source code is available at GitHub.

Источник

Delete a Directory Recursively in Java

announcement - icon

As always, the writeup is super practical and based on a simple application that can work with documents with a mix of encrypted and unencrypted fields.

We rely on other people’s code in our own work. Every day.

It might be the language you’re writing in, the framework you’re building on, or some esoteric piece of software that does one thing so well you never found the need to implement it yourself.

The problem is, of course, when things fall apart in production — debugging the implementation of a 3rd party library you have no intimate knowledge of is, to say the least, tricky.

Lightrun is a new kind of debugger.

It’s one geared specifically towards real-life production environments. Using Lightrun, you can drill down into running applications, including 3rd party dependencies, with real-time logs, snapshots, and metrics.

Learn more in this quick, 5-minute Lightrun tutorial:

announcement - icon

Slow MySQL query performance is all too common. Of course it is. A good way to go is, naturally, a dedicated profiler that actually understands the ins and outs of MySQL.

The Jet Profiler was built for MySQL only, so it can do things like real-time query performance, focus on most used tables or most frequent queries, quickly identify performance issues and basically help you optimize your queries.

Critically, it has very minimal impact on your server’s performance, with most of the profiling work done separately — so it needs no server changes, agents or separate services.

Basically, you install the desktop application, connect to your MySQL server, hit the record button, and you’ll have results within minutes:

announcement - icon

DbSchema is a super-flexible database designer, which can take you from designing the DB with your team all the way to safely deploying the schema.

The way it does all of that is by using a design model, a database-independent image of the schema, which can be shared in a team using GIT and compared or deployed on to any database.

And, of course, it can be heavily visual, allowing you to interact with the database using diagrams, visually compose queries, explore the data, generate random data, import data or build HTML5 database reports.

Get started with Spring 5 and Spring Boot 2, through the Learn Spring course:

> CHECK OUT THE COURSE

1. Introduction

In this article, we’ll illustrate how to delete a directory recursively in plain Java. We’ll also look at some alternatives for deleting directories using external libraries.

2. Deleting a Directory Recursively

Java has an option to delete a directory. However, this requires the directory to be empty. So, we need to use recursion to delete a particular non-empty directory:

  1. Get all the contents of the directory to be deleted
  2. Delete all children that are not a directory (exit from recursion)
  3. For each subdirectory of current directory, start with step 1 (recursive step)
  4. Delete the directory

Let’s implement this simple algorithm:

boolean deleteDirectory(File directoryToBeDeleted) < File[] allContents = directoryToBeDeleted.listFiles(); if (allContents != null) < for (File file : allContents) < deleteDirectory(file); >> return directoryToBeDeleted.delete(); >

This method can be tested using a straightforward test case:

@Test public void givenDirectory_whenDeletedWithRecursion_thenIsGone() throws IOException

The @Before method of our test class creates a directory tree with subdirectories and files at pathToBeDeleted location and @After method cleans up directory if required.

Next, let’s have a look at how we can achieve deletion using two of the most commonly used libraries – Apache’s commons-io and Spring Framework’s spring-core. Both of these libraries allow us to delete the directories using just a single line of code.

3. Using FileUtils from commons-io

First, we need to add the commons-io dependency to the Maven project:

The latest version of the dependency can be found here.

Now, we can use FileUtils to perform any file-based operations including deleteDirectory() with just one statement:

FileUtils.deleteDirectory(file);

4. Using FileSystemUtils from Spring

Alternatively, we can add the spring-core dependency to the Maven project:

 org.springframework spring-core 4.3.10.RELEASE 

The latest version of the dependency can be found here.

We can use the deleteRecursively() method in FileSystemUtils to perform the deletion:

boolean result = FileSystemUtils.deleteRecursively(file);

The recent releases of Java offer newer ways of performing such IO operations described in the following sections.

5. Using NIO2 With Java 7

Java 7 introduced a whole new way of performing file operations using Files. It allows us to traverse a directory tree and use callbacks for actions to be performed.

public void whenDeletedWithNIO2WalkFileTree_thenIsGone() throws IOException < Path pathToBeDeleted = TEMP_DIRECTORY.resolve(DIRECTORY_NAME); Files.walkFileTree(pathToBeDeleted, new SimpleFileVisitor() < @Override public FileVisitResult postVisitDirectory( Path dir, IOException exc) throws IOException < Files.delete(dir); return FileVisitResult.CONTINUE; >@Override public FileVisitResult visitFile( Path file, BasicFileAttributes attrs) throws IOException < Files.delete(file); return FileVisitResult.CONTINUE; >>); assertFalse("Directory still exists", Files.exists(pathToBeDeleted)); >

The Files.walkFileTree() method traverses a file tree and emits events. We need to specify callbacks for these events. So, in this case, we will define SimpleFileVisitor to take the following actions for the generated events:

  1. Visiting a file – delete it
  2. Visiting a directory before processing its entries – do nothing
  3. Visiting a directory after processing its entries- delete the directory, as all entries within this directory would have been processed (or deleted) by now
  4. Unable to visit a file – rethrow IOException that caused the failure

Please refer to Introduction to the Java NIO2 File API for more details on NIO2 APIs on handling file operations.

6. Using NIO2 With Java 8

Since Java 8, Stream API offers an even better way of deleting a directory:

@Test public void whenDeletedWithFilesWalk_thenIsGone() throws IOException

Here, Files.walk() returns a Stream of Path that we sort in reverse order. This places the paths denoting the contents of directories before directories itself. Thereafter it maps Path to File and deletes each File.

7. Conclusion

In this quick tutorial, we explored different ways of deleting a directory. While we saw how to use recursion to delete, we also looked at some libraries, NIO2 leveraging events and Java 8 Path Stream employing a functional programming paradigm.

All source code and test cases for this article are available over on GitHub.

announcement - icon

Slow MySQL query performance is all too common. Of course it is. A good way to go is, naturally, a dedicated profiler that actually understands the ins and outs of MySQL.

The Jet Profiler was built for MySQL only, so it can do things like real-time query performance, focus on most used tables or most frequent queries, quickly identify performance issues and basically help you optimize your queries.

Critically, it has very minimal impact on your server’s performance, with most of the profiling work done separately — so it needs no server changes, agents or separate services.

Basically, you install the desktop application, connect to your MySQL server, hit the record button, and you’ll have results within minutes:

Источник

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.

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:

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

Источник

Оцените статью