我是以编程方式删除它..在删除之前,需要检查它是否已打开
我想要这样的东西,
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();
}
答案 0 :(得分: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