Java code cannot delete file

My Java code cannot delete files on the system hard drive.

Whenever the file.delete() function is file.delete() , it returns false . Any ideas why this might happen?

+4
source share
7 answers

File.delete() may not delete the file for many reasons, including:

  • you do not have the correct permissions to delete the file
  • the file is a directory, and the directory is not empty.
  • the file is locked by another process (or even by the same process, for example, in an unclosed FileOutputStream )
  • file does not exist
+12
source

File.delete() may return false if you are trying to delete a directory that is not empty, or the named file simply does not exist during the call.

(if there is a permission problem, a SecurityException is thrown)

+5
source

I had the same problem in my code, and I found that the culprit was actually an unclosed FileInputStream. After closing this FIS, my file was deleted without problems. Hope this helps someone.

+2
source

The usual reasons are insufficient permissions (although this usually throws an exception), trying to delete a nonexistent file or trying to delete a non-empty directory. Are you completely sure that you have permissions to delete the file you are trying to delete?

+1
source

Some process may be reading / writing a file, so it is locked. Or then your process does not have permission to delete the file. If the file is a directory, all files inside it must be deleted before the directory can be deleted. And finally, there is a situation where the file does not exist, so the delete method will return false.

+1
source

Windows? Use Process Explorer to search for all processes that save a descriptor (lock) in a file (or if it is a directory in any file inside it).

On Linux, use fuser .

+1
source

Perhaps you are trying to delete any file that exists in C: Disk, and on which you may not have rights to do this. Try putting it on any drive other than C: and then run your code. Hope this works for you. :)

0
source

All Articles