How to delete a file in Java
There are two methods to delete a file in Java:
- Using File.delete() method
- Using File.deleteOnExit() method
Java File.delete() method
In Java, we can delete a file by using the File.delete() method of File class. The delete() method deletes the file or directory denoted by the abstract pathname. If the pathname is a directory, that directory must be empty to delete. The method signature is:
The method returns true if the file or directory deleted successfully, otherwise returns false.
Example
Output:
When the file exist.
When the file does not exist.
Java File.deleteOnExit() method
The File.deleteOnExit() method also deletes the file or directory defined by abstract pathname. The deleteOnExit() method deletes file in reverse order. It deletes the file when JVM terminates. It does not return any value. Once the request has been made, it is not possible to cancel the request. So this method should be used with care.
The method signature is:
Usually, we use this method when we want to delete the temporary file. A temporary file is used to store the less important and temporary data, which should always be deleted when JVM terminates.
If we want to delete the .temp file manually, we can use File.delete() method.
Example
The following example creates a temporary file named abc.temp and delete it when the program is terminated.
Output:
Let’s see another example that deletes text file.
Example
Output: