如何检查文件是否可以删除? [英] How to check if a file can be deleted?
本文介绍了如何检查文件是否可以删除?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我如何检查我可以用Java删除文件?
How can I check that I can delete a file in Java?
例如,如果文件 test.txt
在另一个程序中打开我无法删除它。我必须在实际删除之前知道它,所以我不能这样做:
For example, if a file test.txt
is opened in another program I can't delete it. And I have to know it before actual deletion, so I can't do this:
if (!file.delete()) { ... }
和 srcFile.canWrite()
也不起作用。
推荐答案
使用Write Lock打开文件。
Open the file with a Write Lock.
请参阅此处 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();
这篇关于如何检查文件是否可以删除?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文