Alex Blundell
Alex Blundell

Reputation: 2104

Java not deleting a file which was created by itself

I've seen similar questions on here about File.delete() not working as expected, however this is slightly different in the way that Java has actually created the File, but won't delete it after it's finished with it.

File genFile = new File(parsed);
... sends file data across socket ... 
genFile.delete();

The generated file (genFile) was generated earlier in the program and written to, however when I try to delete it, the file just remains in the directory - no error messages etc. Any ideas as to what could be happening?

Upvotes: 0

Views: 109

Answers (4)

Richard Sitze
Richard Sitze

Reputation: 8463

If you're running under Windows or *Unix then that bit of information would be relevant.

Windows will not remove a file that is open by any application; close the file before removing.

Unix variants should go ahead and remove the file (release the inode).

Upvotes: 0

Kishore
Kishore

Reputation: 839

Add

genFile.close();

before

genFile.delete();

The stream would not have been flushed when you try to delete the file, so close the stream first and delete the file.

Upvotes: 0

Ankit
Ankit

Reputation: 6622

you need to close() the file connection before trying to delete()

Upvotes: 0

ZhongYu
ZhongYu

Reputation: 19682

File.delete() is bad, since it is silent about errors.

Try

java.nio.file.Files.delete(file.toPath());  // throws IOException

it might show you the reason why file can't be deleted. (or it might not:)

Upvotes: 1

Related Questions