如果存在,Java更好的删除文件的方法 [英] Java better way to delete file if exists
问题描述
在我们删除文件之前,我们需要在 file.delete()
之前调用 file.exists()
例如
We need to call file.exists()
before file.delete()
before we can delete a file E.g.
File file = ...;
if (file.exists()){
file.delete();
}
目前在我们的所有项目中,我们在一些util类中创建一个静态方法来包装这段代码。是否有其他方法可以实现相同的目标,因此我们不需要在每个其他项目中复制我们的utils文件。
Currently in all our project we create a static method in some util class to wrap this code. Is there some other way to achieve the same , so that we not need to copy our utils file in every other project.
推荐答案
从Java 7开始,您可以使用 deleteIfExists ,它返回一个布尔值(或抛出异常),具体取决于文件是否被删除。对于其他文件系统操作,此方法可能不是原子的。此外,如果JVM /其他程序正在使用某个文件,那么在某些操作系统上它将无法将其删除。每个文件都可以通过 toPath
方法转换为路径。例如。
Starting from Java 7 you can use deleteIfExists that returns a boolean (or throw an Exception) depending on whether a file was deleted or not. This method may not be atomic with respect to other file system operations. Moreover if a file is in use by JVM/other program then on some operating system it will not be able to remove it. Every file can be converted to path via toPath
method . E.g.
File file = ...;
boolean result = Files.deleteIfExists(file.toPath()); //surround it in try catch block
这篇关于如果存在,Java更好的删除文件的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!