Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if I can delete a file?

How can I check that I can delete a file in Java?

For example, I should be able to delete file C:/file.txt but I never will be able to delete the C:/ or Computer, or My Documents etc.

Solution described in possible duplicate does not work for me.

like image 287
SeniorJD Avatar asked May 14 '13 09:05

SeniorJD


2 Answers

Removing file requires write permission of the file's parent, i.e. directory where file is stored. Directory in java is also represented by instance of class java.io.File that has method canWrite().

So, to check whether file can be deleted you should call file.getParent().canWrite().

like image 124
AlexR Avatar answered Nov 08 '22 16:11

AlexR


On my Windows 7 64 bit box using NTFS and Java 7 (Oracle JDK), the only thing which worked for me reliably is

boolean canDelete = file.renameTo(file)

This is surprisingly simple and works also for folders, which have "somewhere below" an "open" or "locked" file.

Other things I tried and produced false-positives: aquire a FileLock, File#canWrite, File#setLastModified ("touch"), file.getParent().canWrite()

like image 43
Peti Avatar answered Nov 08 '22 16:11

Peti