Delete directory in Java

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

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:

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.

Add Comment