如何在java中打开或不打开文件是不行的

时间:2016-05-05 05:05:47

标签: java file filechannel filelock apache-commons-io

我尝试使用以下示例在java中检查文件是否已打开。我使用Apache Commons IO库...

boolean isFileUnlocked = false;
try {
    org.apache.commons.io.FileUtils.touch(yourFile);
    isFileUnlocked = true;
} catch (IOException e) {
    isFileUnlocked = false;
}

if(isFileUnlocked){
    // Do stuff you need to do with a file that is NOT locked.
} else {
    // Do stuff you need to do with a file that IS locked
}

这给我带来了错误的结构。当我没有打开确切的文件时,这显示我已打开文件。如果未打开文件,则结果为false,这是不可能的。

其他例子在这里,

public boolean isFileOpened(File file){
  boolean res = false;
  FileChannel channel = new RandomAccessFile(file, "rw").getChannel();
  // Get an exclusive lock on the whole file
  FileLock lock = channel.lock();
  try {
      //The file is not already opened 
      lock = channel.tryLock();
   } catch (OverlappingFileLockException e) {
    // File is open by someone else
    res = true;
   } finally {
    lock.release();
   }
  return res;
}

这也给我带来了不正确的信息。

我从这里得到这些例子Java: Check if file is already open

现在我的问题是如何在java中正确检查文件是否被打开?

谢谢。

0 个答案:

没有答案