Program
import java.io.File; public class FileDelete { public static void main(String[] args) { File file = new File("C:\\Users\\Dev\\Desktop\\1.txt"); file.deleteOnExit(); System.out.println(file+":- This file will delete on exit."); if(file.delete()) { System.out.println("File deleted successfully"); } else { System.out.println("Failed to delete the file"); } } }
Output:
<br>C:\Users\Dev\Desktop\1.txt:- This file will delete on exit.<br>Failed to delete the file
Description
public boolean delete()
Deletes the file or directory denoted by this abstract pathname. If this pathname denotes a directory, then the directory must be empty in order to be 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.
Returns:
true if and only if the file or directory is successfully deleted; false otherwise
Throws:
SecurityException – If a security manager exists and its SecurityManager.checkDelete(java.lang.String) method denies delete access to the file
deleteOnExit
public void deleteOnExit()
Requests that the file or directory denoted by this abstract pathname be deleted when the virtual machine terminates. Files (or directories) are deleted in the reverse order that they are registered. Invoking this method to delete a file or directory that is already registered for deletion has no effect. Deletion will be attempted only for normal termination of the virtual machine, as defined by the Java Language Specification.
Once deletion has been requested, it is not possible to cancel the request. This method should therefore be used with care.
Note:
this method should not be used for file-locking, as the resulting protocol cannot be made to work reliably. The FileLock facility should be used instead.
Throws:
SecurityException – If a security manager exists and its SecurityManager.checkDelete(java.lang.String) method denies delete access to the file