How to determine if another process is using the file (Java)

I tried many examples, but no one worked

I also try to use trylock() It always returns false Why?

private boolean checkCompleteFile(File f)
{           
    RandomAccessFile file = null;
    FileLock fileLock = null;

    try
    {
        file = new RandomAccessFile(f,"rw");
        FileChannel fileChannel = file.getChannel();

        fileLock = fileChannel.lock();
        if (fileLock != null)
        {
            fileLock.release();
            file.close();
            return false;
        }

    }
    catch(Exception e)
    {
         return false;
    }

    return true;
}

Solution

You catch an exception and return false, which is why you are always false. Do something about the exception or don't catch it, so you know whether to throw an exception. If you catch a general exception, the return value of the error is actually meaningless

try {
  lock = channel.tryLock();
  // ...
} catch (OverlappingFileLockException e) {
  // File is already locked in this thread or virtual machine
}
lock.release();
channel.close();

You can try to access the file and catch an exception if it fails:

boolean isLocked=false;
RandomAccessFile fos=null;
try {
      File file = new File(filename);
      if(file.exists())
        fos=new RandomAccessFile(file,"rw");        
}catch (FileNotFoundException e) {
    isLocked = true;
}catch (SecurityException e) {
    isLocked = true;
}catch (Exception e) {
    // handle exception
}finally {
    try {
        if(fos!=null) {
            fos.close();
        }
    }catch(Exception e) {
        //handle exception
    }
}

Note that the RandomAccessFile class throws:

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>