This post will discuss how to delete a file in Java.

There are several ways to delete a file in plain Java and using third-party libraries. These are discussed below in detail:

1. Using File Class

Before Java 7, we can use the File.delete() method for deleting a given file. The method returns true if the file is successfully deleted and returns false if the file doesn’t exist or in case of an I/O error. This method doesn’t throw an IOException when a file deletion fails.

Download Code

2. Using NIO

Starting from Java 7, we can use the deleteIfExists() method of the Files class that deletes a file if it exists. It returns true if the file was deleted by this method, and an IOException is thrown if an I/O error occurs. If the file doesn’t exist, false is returned by the function, but no exception is thrown.

Download Code

 
The Files class defines the delete method to throw an IOException when a file cannot be deleted, which is very useful for error reporting and to diagnose why a file cannot be deleted.

Download Code

3. Using Apache Commons IO

FileUtils class from Apache Commons IO library has the forceDelete() method to delete a file. If the file already exists, then java.io.FileNotFoundException is thrown, and IOException is thrown if deletion is unsuccessful.

Download Code

That’s all about deleting a file in Java.