How to check if a file can be deleted?
How can I check that I can delete a file in Java?
For example, if a file test.txt
is opened in another program I can't delete it. 开发者_StackOverflow中文版And I have to know it before actual deletion, so I can't do this:
if (!file.delete()) { ... }
And srcFile.canWrite()
is not working either.
On my Windows 7 64 bit box using NTFS and Java 7, 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")
Open the file with a Write Lock.
See here http://download.oracle.com/javase/6/docs/api/java/nio/channels/FileLock.html
FileChannel channel = new RandomAccessFile("C:\\foo", "rw").getChannel();
// Try acquiring the lock without blocking. This method returns
// null or throws an exception if the file is already locked.
FileLock lock = channel.tryLock();
// ...
// release it
lock.release();
Under Unix, you need write permission to the parent directory in order to delete a file.
Under Windows, permissions can be a lot more fine-grained, but write-access to the directory would catch most cases there as well, I believe. In addidtion, you should try and aqquire a write-lock on the file when under windows.
You might want to look into FileLock. There is a FileChannel.tryLock() method that will return null if you cannot obtain a lock.
精彩评论