We need to call file.exists()
before file.delete()
before we can delete a file E.g.
File file = ...;
if (file.exists()){
file.delete();
}
Currently in all our project we create a static method in some util class to wrap this code. Is there some other way to achieve the same , so that we not need to copy our utils file in every other project.
This question is related to
java
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();
}
file.delete();
if the file doesn't exist, it will return false.
This is my solution:
File f = new File("file.txt");
if(f.exists() && !f.isDirectory()) {
f.delete();
}
Use the below statement to delete any files:
FileUtils.forceDelete(FilePath);
Note: Use exception handling
codes if you want to use.
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.
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();
}
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.
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;
}
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"));
Source: Stackoverflow.com