Java better way to delete file if exists

后端 未结 10 631
慢半拍i
慢半拍i 2020-12-24 10:21

We need to call file.exists() before file.delete() before we can delete a file E.g.

 File file = ...;
 if (file.exists()){
     fil         


        
10条回答
  •  情话喂你
    2020-12-24 11:15

    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
    

提交回复
热议问题