Java’s better way to delete files (if any)
•
Java
We need to be in file Delete () before calling file. Exists() before deleting the file
File file = ...; if (file.exists()){ file.delete(); }
Currently in all our projects, we create a static method in some util classes to wrap this code There are no other ways to implement the same, so we don't need to copy our utils files in other projects
Solution
Starting with Java 7, you can use deleteifexists to return a Boolean value (or throw an exception), depending on whether the file is deleted This method may not be atomic
File =; boolean result = Files. deleteIfExists(file.toPath()); // Enclose it in a try catch block
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码