Java better way to delete file if exists

后端 未结 10 651
慢半拍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: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;
    }
    

提交回复
热议问题