Delete a directory in Java
This post will discuss how to recursively delete a directory in Java.
There are several ways to delete a directory and all its subdirectories in Java and using third-party libraries such as Apache Commons IO and Guava. These are discussed below in detail:
1. Using Apache Commons IO
Apache Commons IO’s FileUtils class provides several utility methods for working with files. To delete a directory recursively, we can use its deleteDirectory(File directory) method. It takes a directory to delete and throws an IOException if the deletion is unsuccessful.
If the specified directory contains a symbolic link (on Unix/Linux machines), it deletes the link itself but won’t follow the link and deletes all the files the link points to.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
import org.apache.commons.io.FileUtils; import java.io.File; import java.io.IOException; class Main { public static void main(String[] args) { File file = new File("/var/www/html/"); try { FileUtils.deleteDirectory(file); System.out.println("Directory deleted successfully."); } catch (IOException e) { e.printStackTrace(); } } } |
To avoid catching an exception, the deleteQuietly(File directory) method can quietly delete a directory and all its subdirectories.
We can also use forceDelete(File file) method of the FileUtils class. It works similarly to the FileUtils::deleteDirectory method.
2. Using Guava Library
With Guava 21.0, we can use the MoreFiles class, which provides several static utilities for Path instances. We can use the deleteRecursively(Path path) method to deletes the directory at the given path recursively. With symbolic links, the link is deleted and not the target of the link.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
import com.google.common.io.MoreFiles; import com.google.common.io.RecursiveDeleteOption; import java.io.File; import java.io.IOException; import java.nio.file.Path; class Main { public static void deleteDirectory(Path directory) throws IOException { MoreFiles.deleteRecursively(directory, RecursiveDeleteOption.ALLOW_INSECURE); } public static void main(String[] args) { File file = new File("/var/www/html/"); try { deleteDirectory(file.toPath()); System.out.println("Directory deleted successfully."); } catch (IOException e) { e.printStackTrace(); } } } |
3. Using Files Class
With Java 7, Files.delete(Path path) method can be used with the java.nio.file.Files.walkFileTree(…) method to delete a directory and all entries in it. The following example demonstrates the usage of these methods to delete a directory:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 |
import java.io.File; import java.io.IOException; import java.nio.file.*; import java.nio.file.attribute.BasicFileAttributes; class Main { public static void deleteDirectory(Path directory) throws IOException { if (Files.exists(directory)) { Files.walkFileTree(directory, new SimpleFileVisitor<Path>() { @Override public FileVisitResult visitFile(Path path, BasicFileAttributes attr) throws IOException { Files.delete(path); return FileVisitResult.CONTINUE; } @Override public FileVisitResult postVisitDirectory(Path path, IOException ex) throws IOException { Files.delete(path); return FileVisitResult.CONTINUE; } }); } } public static void main(String[] args) { File file = new File("/var/www/html/"); try { deleteDirectory(file.toPath()); System.out.println("Directory deleted successfully."); } catch (IOException e) { e.printStackTrace(); } } } |
4. Using Java 8
With Java 8, we can use the java.nio.file.Files.walk(…) method that returns a Stream of Path objects by walking the file tree in a depth-first manner is rooted at a given starting file.
The following code shows how to use the Files.walk(…) method with the File.delete() method to recursively delete the specified directory and all its subdirectories. Since the file tree is traversed depth-first manner and File::delete won’t allow deleting a non-empty directory, we have used a reverse order comparator to ensure the parent directory is deleted after the child.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
import java.io.File; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.util.Comparator; class Main { public static void deleteDirectory(Path directory) throws IOException { Files.walk(directory) .sorted(Comparator.reverseOrder()) .map(Path::toFile) .forEach(File::delete); } public static void main(String[] args) { File file = new File("/var/www/html/"); try { deleteDirectory(file.toPath()); System.out.println("Directory deleted successfully."); } catch (IOException e) { e.printStackTrace(); } } } |
5. Java 6
In Java 6 and before, we can write a custom routine to delete a directory recursively. Here’s a working example:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
import java.io.File; import java.nio.file.Files; class Main { public static void deleteDirectory(File file) { if (file.isDirectory()) { File[] contents = file.listFiles(); for (File f: contents) { deleteDirectory(f); } } file.delete(); } public static void main(String[] args) { File file = new File("/var/www/html/"); deleteDirectory(file); System.out.println("Directory deleted successfully."); } } |
6. Using Runtime Class
Every Java application has a single instance of the Runtime class, and we can obtain the current runtime from the getRuntime() method. We can use the Runtime.exec(command) convenience method to execute the corresponding remove directory command of the underlying environment.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
import java.io.File; import java.io.IOException; class Main { public static void deleteDirectory(File file) throws IOException { System.out.println(file.getAbsolutePath()); if (file.exists()) { String cmd = "rm -r " + file.getAbsolutePath(); Runtime.getRuntime().exec(cmd); } } public static void main(String[] args) { File file = new File("/var/www/html/"); try { deleteDirectory(file); System.out.println("Directory deleted successfully."); } catch (IOException e) { e.printStackTrace(); } } } |
That’s all about deleting a directory in Java.
Also See:
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)