How to determine if a file is being used by another process (Java)

I tried many examples, but no one works. I try this but not work.

I also tried 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;
}
+5
source share
3 answers

You detect an exception and return false, so you become false all the time, do something with the exception or don’t catch it so that you know if the exception was thrown, if you catch the general exception, the false return value does not make sense.

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

You smoke, just try to access the file and catch the exception if it is not satisfied:

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:

FileNotFoundException -

"r", , "rw" , , .

SecurityException -

checkRead "rw", checkWrite

+2

:

try {
    @SuppressWarnings("resource")
    FileChannel channel = new RandomAccessFile(fileToRead, "rw").getChannel();
    //This method blocks until it can retrieve the lock. 
    FileLock lock = channel.lock(); // Try acquiring the lock without blocking. 
    try { 
        lock = channel.tryLock();
    } catch (OverlappingFileLockException e){

    }
    lock.release(); //close the file.
    channel.close();
} catch (Exception e) {             

}
+1

linux?

lsof -p 

, , , .

0

All Articles