Java better way to delete file if exists

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

    There's also the Java 7 solution, using the new(ish) Path abstraction:

    Path fileToDeletePath = Paths.get("fileToDelete_jdk7.txt");
    Files.delete(fileToDeletePath);
    

    Hope this helps.

    0 讨论(0)
  • 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"));
    
    0 讨论(0)
  • 2020-12-24 11:13

    This is my solution:

    File f = new File("file.txt");
    if(f.exists() && !f.isDirectory()) { 
        f.delete();
    }
    
    0 讨论(0)
  • 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
    
    0 讨论(0)
提交回复
热议问题