public static void delete(Path path)throws IOException
Deletes a file.
An implementation may require to examine the file to determine if the file is a directory. Consequently this method may not be atomic with respect to other file system operations. If the file is a symbolic link then the symbolic link itself, not the final target of the link, is deleted.
If the file is a directory then the directory must be empty. In some implementations a directory has entries for special files or links that are created when the directory is created. In such implementations a directory is considered empty when only the special entries exist. This method can be used with the walkFileTree method to delete a directory and all entries in the directory, or an entire file-tree where required.
On some operating systems it may not be possible to remove a file when it is open and in use by this Java virtual machine or other programs.
Parameters:
path – the path to the file to delete
Throws:
NoSuchFileException – if the file does not exist (optional specific exception)
DirectoryNotEmptyException – if the file is a directory and could not otherwise be deleted because the directory is not empty (optional specific exception)
IOException – if an I/O error occurs
SecurityException – In the case of the default provider, and a security manager is installed, the SecurityManager.checkDelete(String) method is invoked to check delete access to the file
package com.candidjava.filenio; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; public class DeleteFile { public static void main(String[] args) { Path path=Paths.get("F:/Filesnio/create.txt"); try { Files.delete(path); System.out.println("File deleted successfully"); } catch (Exception e) { // TODO: handle exception e.printStackTrace(); } } }
Old Approach
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
package com.candidjava.file; import java.io.File; public class DeleteFile { public static void main(String[] args) { boolean result; try { File file = new File("F:/Files/sample.txt"); result = file.delete(); if (result) { System.out.println("File deleted successfully"); } else { System.out.println("File deletion failed"); } } catch (Exception e) { // TODO: handle exception e.printStackTrace(); } } }