0

I try to check file is opened or not in java using following examples . I use Apache Commons IO library...

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
}

This brings me a wrong formation . When I am not opened the exact file, this show me the file has opened. If file is not opened, result is false and this cannot be possible .

Other example is here,

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;
}

This also brings me incorrect information.

I get these examples from here Java: Check if file is already open

Now my problem is how could I check file is opened or not in java correctly ?

Thank you.

Community
  • 1
  • 1
Terance Wijesuriya
  • 1,928
  • 9
  • 31
  • 61

0 Answers0