In the previous tutorial, I showed you how to create a new directory in Java. In this tutorial, I will guide you with some ways to delete a folder!
The first is that we can use the File object.
Deleting a directory in Java using the File object is a bit more complicated. The File object itself gives us a method called delete(), but this method only deletes empty directories. If the directory contains files and other subfolders, then when we call this method, Java will immediately report the error.
But okay, the following method will help you delete a folder completely without worrying
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 |
public boolean delete(File folder) { // Check null for folder variable if (folder == null) return false; // Check folder is existing or not if (!folder.exists()) return true; // Check passing folder is folder or not if (!folder.isDirectory()) return false; // First, we will get all files and sub-folder to delete them String[] list = folder.list(); if (list != null) { for (int i = 0; i < list.length; i++) { File entry = new File(folder, list[i]); // If is sub-folder, call again this method to delete this sub-folder if (entry.isDirectory()) { if (!delete(entry)) return false; } else { if (!entry.delete()) return false; } } } // Finally, delete passing folder return folder.delete(); } |
The second way is to use the Files object.
From the Java 7, the Files object also provides a static method of delete() with the parameter passed as the Paths object that helps us to delete a directory easily. Of course, the folder you want to delete is also empty.
For example:
1 2 |
Path dir = Paths.get("F:/test/test2/test3"); Files.delete(dir); |
If the directory you are importing is not empty, we will run into the error!
In addition to the delete() method, the Files object provides us with another method, called deleteIfExists(), to delete the directory. With this method, whether the directory you exist or not, the program does not occur error.
1 2 |
Path dir = Paths.get("F:/test/test2/test3"); Files.deleteIfExists(dir); |