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) {
}finally {
try {
if(fos!=null) {
fos.close();
}
}catch(Exception e) {
}
}
Note that the RandomAccessFile class throws:
FileNotFoundException -
"r", , "rw" , , .
SecurityException -
checkRead "rw", checkWrite