The deleteIfExists() method of java.nio.file.Files help us to delete a file if the file exists at the path. we pass the path of the file as a parameter to this method. This method will return true if the file was deleted by this method; false if the file could not be deleted because it did not exist.
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 this method will delete that file only when the directory is 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. In such cases, Directories can be delete using this method. 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.
public static boolean deleteIfExists(Path path) throws IOException
Parameters: This method accepts a parameter path which is the path to the file to deleted.
Return value: This method returns true if the file was deleted by this method; false if the file could not be deleted because it did not exist.
Exception: This method will throw following exceptions:
- DirectoryNotEmptyException – if the file is a directory and could not otherwise be deleted because the directory is not empty
- 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 to delete access to the file
Below programs illustrate deleteIfExists(Path) method:
Before deleting the file: The file is present in the path “D:\\Work\\Test\\file1.txt”
- Files size() method in Java with Examples
- Files isExecutable() method in Java with Examples
- Files isReadable() method in Java with Examples
- Files isHidden() method in Java with Examples
- Files isWritable() method in Java with Examples
- Files getFileStore() method in Java with Examples
- Files delete() method in Java with Examples
- Jar files in Java
- How to rename all files of a folder using Java?
- Working with JAR and Manifest files In Java
- Compressing and Decompressing files in Java
- Java program to merge two files into a third file
- Java program to merge two files alternatively into third file
- Java program to merge contents of all the files in a directory
- Compressing and Decompressing files using GZIP Format in java
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.