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.
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()
.
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()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With