Java better way to delete file if exists

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

    Use the below statement to delete any files:

    FileUtils.forceDelete(FilePath);
    

    Note: Use exception handling codes if you want to use.

    0 讨论(0)
  • 2020-12-24 10:50
      File xx = new File("filename.txt");
        if (xx.exists()) {
           System.gc();//Added this part
           Thread.sleep(2000);////This part gives the Bufferedreaders and the InputStreams time to close Completely
           xx.delete();     
        }
    
    0 讨论(0)
  • 2020-12-24 10:58

    Use Apache Commons FileUtils.deleteDirectory() or FileUtils.forceDelete() to log exceptions in case of any failures,

    or FileUtils.deleteQuietly() if you're not concerned about exceptions thrown.

    0 讨论(0)
  • 2020-12-24 10:59
    file.delete();
    

    if the file doesn't exist, it will return false.

    0 讨论(0)
  • 2020-12-24 11:01

    if you have the file inside a dirrectory called uploads in your project. bellow code can be used.

    Path root = Paths.get("uploads");
    File existingFile = new File(this.root.resolve("img.png").toUri());
    
    if (existingFile.exists() && existingFile.isFile()) {
         existingFile.delete();
       }
    

    OR

    If it is inside a different directory this solution can be used.

    File existingFile = new File("D:\\<path>\\img.png");
    
    if (existingFile.exists() && existingFile.isFile()) {
        existingFile.delete();
      }
    
    0 讨论(0)
  • 2020-12-24 11:02

    I was working on this type of function, maybe this will interests some of you ...

    public boolean deleteFile(File file) throws IOException {
        if (file != null) {
            if (file.isDirectory()) {
                File[] files = file.listFiles();
    
                for (File f: files) {
                    deleteFile(f);
                }
            }
            return Files.deleteIfExists(file.toPath());
        }
        return false;
    }
    
    0 讨论(0)
提交回复
热议问题