Java better way to delete file if exists

后端 未结 10 636
慢半拍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:06

    Apache Commons IO's FileUtils offers FileUtils.deleteQuietly:

    Deletes a file, never throwing an exception. If file is a directory, delete it and all sub-directories. The difference between File.delete() and this method are:

    • A directory to be deleted does not have to be empty.
    • No exceptions are thrown when a file or directory cannot be deleted.

    This offers a one-liner delete call that won't complain if the file fails to be deleted:

    FileUtils.deleteQuietly(new File("test.txt"));
    

提交回复
热议问题