2

I am trying to delete a file using File.delete()

Here is my code:

File stagingFile = new File(stagingPath,configFileName);
FileOutputStream fos = new FileOutputStream(stagingFile);
int c = 0;
while((c=input.read())!=-1){
    fos.write(c);
}
fos.flush();
fos.close();
input.close();

And after performing some operations, I do this:

boolean delete = stagingFile.delete();

delete returns false. As far as I can see I've closed all handlers relating to stagingFile. I'm not sure why it doesn't get deleted

Chaos
  • 11,213
  • 14
  • 42
  • 69
  • You could use Files.delete( [path] ) method to get an IOException when the delete fails, and that should tell you why the file cannot be deleted. – Seth Hoenig Aug 15 '13 at 21:17
  • NB your copy code is as inefficient as it could be. Use a `BufferedInputStream` and a `BufferedOutputStream` around the File streams, or read/write to/from a `byte[]` array, taking care to use the count returned by `read()` correctly. – user207421 Aug 16 '13 at 00:18

2 Answers2

5

From the File.delete docs:

Note that the Files class defines the delete method to throw an IOException when a file cannot be deleted. This is useful for error reporting and to diagnose why a file cannot be deleted.

Give this method (Files.delete(Path)) a shot.

Nick Veys
  • 23,458
  • 4
  • 47
  • 64
1

Another idea: use createTempFile() to create a temporary file in the first place. After that, use Files.delete() to delete the file.

Óscar López
  • 232,561
  • 37
  • 312
  • 386