Delete a File Using Java
Java provides methods to delete files using java programs. On the contrary to normal delete operations in any operating system, files being deleted using the java program are deleted permanently without being moved to the trash/recycle bin.
Methods used to delete a file in Java:
1. Using java.io.File.delete() function: Deletes the file or directory denoted by this abstract pathname.
public boolean delete()
Returns: It returns true if and only if the file or the directory is successfully deleted; false otherwise
File deleted successfully
2. Using java.nio.file.files.deleteifexists(Path p) method defined in Files package: This method deletes a file if it exists. It also deletes a directory mentioned in the path only if the directory is not empty.
public static boolean deleteIfExists(Path path) throws IOException
Parameters: path – the path to the file to delete
Returns: It returns true if the file was deleted by this method; false if it could not be deleted because it did not exist.
- 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.
This article is contributed by Mayank Kumar. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.