In this article, we are going to present several ways to delete files in Java using
JDK 6, 7 and
Apache Commons IO library. Removing files is common functionality often used in applications to clean up not used resources.
This article is a part of the Java IO Tutorial.
2. Delete the file using
Starting with the old school way:
In this example, we created an instance of
File object and made use of its
delete() method. The method returns true if delete operation was successful, otherwise false. We will get the negative result when a file doesn't exist.
3. Removing files in
JDK 7 the modern
Files class was introduced. The following example shows how to use it:
If the file does not exist,
Files.delete(...) method will throw an exception
NoSuchFileException. So, in this case, we have a different than in the
JDK 7 approach to handle not existed files.
Apache Commons IO library to remove files
Using external libraries to the simple operations on files might be not the best solution but it is doable and gives us additional options and features:
In this example, we made use of
FilesUtils.deleteQuietly(...) method that simply removes the file and returns true if the file was removed successfully.
In case we do want an exception to be throw, we can use
In this article, we illustrated various ways to delete a file in Java. This article covered methods used in
JDK 6, 7 and presented in
Apache Commons IO library.
Code snippets used in this article are available under the GitHub repository.