Thursday, August 13, 2015

Check file is open (lock) or not in Java

RandomAccessFile rf = new RandomAccessFile(file, "rw");
FileChannel fileChannel = rf.getChannel();
FileLock lock = null;
try {
        // let us try to get a lock. If file already has an exclusive lock by another process
        LOGGER.info("Trying to acquire lock");
        lock = fileChannel.tryLock();
        if (lock != null) {
              success = true;
        }
} catch (Exception ex) {
         LOGGER.error(ex.getMessage());
} finally {
         if (lock != null) {
               lock.release();
         }
         if(fileChannel != null){
               fileChannel.close();
         }
          if(rf != null){
               rf.close();
          }
}

No comments:

Post a Comment