We need to call file.exists()
before file.delete()
before we can delete a file E.g.
File file = ...;
if (file.exists()){
fil
Use the below statement to delete any files:
FileUtils.forceDelete(FilePath);
Note: Use exception handling
codes if you want to use.
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();
}
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.
file.delete();
if the file doesn't exist, it will return false.
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();
}
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;
}