Reputation: 190
I have use File delete to delete a file in my local folder however upon executing the line, it doesn't delete right away instead it delete right after I end my application or an error occurs.
After executing the delete line i.e myfile.delete(), the file in my local folder is unable to delete manually as it appear to be used by some other application.
Is there other way that I can delete the file immediately?
String localFilePath = "C:\\Desktop\\smefile.txt";
File file = new File(localFilePath);
if(file.delete()){
System.out.prinln("success");
}
else{
System.out.println("failure");
}
Upvotes: 1
Views: 1326
Reputation: 3026
You must be using that file somewhere in your application.
An open file can't be deleted.
You can try using windows way to delete a file using below method
Runtime.getRuntime().exec(new String[]{"del", "C:\Desktop\smefile.txt"})
If you are even unable to delete that file using above method, its sure that you have opened that file somewhere in your application.
Upvotes: 1
Reputation: 767
you can also try this Files.delete(path);
try {
Files.delete(localFilePath);
} catch (NoSuchFileException x) {
System.err.format("%s: no such" + " file or directory%n", path);
} catch (DirectoryNotEmptyException x) {
System.err.format("%s not empty%n", path);
} catch (IOException x) {
// File permission problems are caught here.
System.err.println(x);
}
Upvotes: 0