- 如何在我尝试删除文件/文件夹之前检查它是否打开。
正在以编程方式删除它..在删除之前,需要检查它是否打开
我想要这样的东西
if(file/folder is open){ //do not delete it }else{ //delete it }
我尝试了下面的两个代码集,但没有任何效果
File scrptFile=new File(dirFile); boolean isFileUnlocked = false; try { org.apache.commons.io.FileUtils.touch(scrptFile); isFileUnlocked = true; } catch (IOException e) { isFileUnlocked = false; } if(isFileUnlocked){ // Do stuff you need to do with a file that is NOT locked. System.out.println("file is not locked"); } else { // Do stuff you need to do with a file that IS locked System.out.println("file is locked"); } File file = new File(dirFile); FileChannel channel = new RandomAccessFile(file, "rw").getChannel(); // Get an exclusive lock on the whole file FileLock lock = channel.lock(); try { lock = channel.tryLock(); // Ok. You get the lock System.out.println("Ok. You get the lock"); } catch (OverlappingFileLockException e) { // File is open by someone else System.out.println("File is open by someone else"); } finally { lock.release(); }
问问题
1261 次
1 回答
0
您可以使用 Apache commons io api,
boolean flagFileNotInUse = false;
try {
org.apache.commons.io.FileUtils.touch(yourFile);
flagFileNotInUse = true;
} catch (IOException e) {
flagFileNotInUse = false;
}
// 然后检查 flagFileNotInUse 的值,
flagFileNotInUse = true, means file not in use
flagFileNotInUse = false, means file in use
于 2013-11-05T07:41:46.350 回答