1

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");
}
isme
  • 190
  • 2
  • 3
  • 18
  • 2
    Are you sure your application itself isn't keeping the file open ? That's the usual reason a file can't be deleted until your application ends. Be sure to close the file if you opened it. – Denys Séguret Jan 11 '17 at 10:11
  • 2
    Under Windows you cannot delete a file that is open. – Thorbjørn Ravn Andersen Jan 11 '17 at 10:11
  • 2
    Desktop is directory right? If it is, you can't remove non-empty directory. Look this implementation: [http://stackoverflow.com/a/779555/3710490](http://stackoverflow.com/a/779555/3710490) – Valijon Jan 11 '17 at 10:12
  • Check if the file is still existing for the JVM after the `delete` – AxelH Jan 11 '17 at 10:12
  • Generally it should delete but only after the file stream using it closes. – Tatarize Jan 11 '17 at 10:12
  • How do I trace which stream is holding it? – isme Jan 11 '17 at 10:21
  • You could use [FileUtils](https://commons.apache.org/proper/commons-io/javadocs/api-release/org/apache/commons/io/FileUtils.html#forceDelete(java.io.File)) – SME_Dev Jan 11 '17 at 10:25
  • Hi guys, I found the answer, your right theres one buffer that is not close in another class. – isme Jan 11 '17 at 10:30

2 Answers2

1

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.

Anil Agrawal
  • 2,748
  • 1
  • 24
  • 31
0

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);
}
Vivien SA'A
  • 727
  • 8
  • 16
  • 1
    Take a look at the javadoc: _On some operating systems it may not be possible to remove a file when it is open and in use by this Java virtual machine or other programs._ – SME_Dev Jan 11 '17 at 10:59