java.io.File delete()
Description
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.
package com.javatutorialhq.java.examples; import java.io.File; import java.io.IOException; /* * This example source code demonstrates the use of * delete() method of File class. * */ public class FileDeleteExample { public static void main(String[] args) { // initialize File object File file = new File("C:javatutorialhqinput.txt"); boolean result; try { // delete the file specified result = file.delete(); // test if successfully deleted the file if (result) { System.out.println("Successfully deleted: " + file.getCanonicalPath()); } else { System.out.println("Failed deleting " + file.getCanonicalPath()); } } catch (IOException e) { e.printStackTrace(); } } }