java.io.File delete()

Description

On this document we will be showing a java example on how to use the delete() method of File Class. This method is basically in place to provide mechanism to delete a file or directory denoted by this abstract pathname. As a general rule, if the abstract pathname denotes a directory, the directory must be empty first in order for it to get deleted.

Note that the Files class defines the delete method to throw an IOException when a file cannot be deleted. This is useful for error reporting and to diagnose why a file cannot be deleted.

Throws:

  • SecurityException – If a security manager exists and its SecurityManager.checkDelete(java.lang.String) method denies delete access to the file

Method Syntax

public boolean delete()

Method Argument

Data Type Parameter Description
N/A N/A N/A

Method Returns

This method returns boolean, true if and only if the file or directory is successfully deleted; false otherwise. This is in place so that you have a way to determine if the file deletion completed or not.

Compatibility

Requires Java 1.0 and up

Java File delete() Example

Below is a java code demonstrates the use of delete() method of File class. The example presented might be simple however it shows the behaviour of the delete() method of File class. Basically we called this method and we put a check on the returned value to check if the file specified has been deleted successfully or not.

The example provided below shows that on the first run, the file has been deleted successfully while on the second run it failed. That is because the file is already deleted on the first run, thus succeeding run will definitely fail as describe on the earlier part of this document.

Sample Output

Below is the sample output when you run the above example.

java lang File delete() example output

Suggested Reading List

References