Java Delete File, directory With Examples

Today we will look into Java delete file and java delete directory examples. Earlier we learned how to create a file in java.

Java delete file

  1. Java File delete() method can be used to delete files or empty directory/folder in java. Java file delete method returns true if file gets deleted and returns false if file doesn’t exist.
  2. If you are trying to delete a directory, it checks java File delete() method check if it’s empty or not. If directory is empty, it gets deleted else delete() method doesn’t do anything and return false. So in this case, we have to recursively delete all the files and then the empty directory.
  3. Another way to delete a non-empty directory is by using Files.walkFileTree() method. In this method, we can process all the files one by one, and call delete method on single files.

Java delete file example

Let’s see java delete file example program.

Below is the output when we execute the above java delete file example program for the first time.

Note that temp directory had file.txt and it got deleted first and then directory was empty and got deleted successfully, /Users/pankaj/project was not empty and hence not deleted.

In the subsequent run of the same program, the output is:

Notice that unlike createNewFile(), delete method doesn’t throw IOException.

Java delete directory

Below is a simple program showing how to delete a non-empty directory. This will work if your directory contains files only.

Java delete directory recursively

Earlier we had to write recursion based code to delete a directory with nested directories. But with Java 7, we can do this using Files class. Below is the code that you should use to delete a directory. It takes care of deleting nested directories too.

That’s all for java delete file and java delete directory examples.

Reference: Java NIO Files Class API Doc

By admin

Leave a Reply