Java FileLock isFileLocked(File file)

Here you can find the source of isFileLocked(File file)

Description

Uses Java 1.4's FileLock class to test for a file lock

License

Open Source License

Parameter

Parameter Description
file a parameter

Declaration

public static boolean isFileLocked(File file) 

Method Source Code

//package com.java2s;
// are made available under the terms of the Eclipse Public License v1.0

import java.io.File;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;

import java.io.IOException;

import java.nio.channels.FileChannel;
import java.nio.channels.FileLock;
import java.nio.channels.OverlappingFileLockException;

public class Main {
    /**//from   w  w  w .j  ava2 s  . com
     * Uses Java 1.4's FileLock class to test for a file lock
     * 
     * @param file
     * @return
     */
    public static boolean isFileLocked(File file) {
        boolean isLocked = false;
        FileOutputStream input = null;
        FileLock lock = null;

        if (!file.exists()) {
            return false;
        }
        try {
            input = new FileOutputStream(file);
            FileChannel fileChannel = input.getChannel();

            lock = fileChannel.tryLock();

            if (lock == null)
                isLocked = true;
            else
                lock.release();
        } catch (Exception e) {
            if (e instanceof SecurityException)
                // Can't write to file.
                isLocked = true;
            else if (e instanceof FileNotFoundException)
                isLocked = false;
            else if (e instanceof IOException)
                isLocked = true;
            // OverlappingFileLockException means that this JVM has it locked
            // therefore it is not locked to us
            else if (e instanceof OverlappingFileLockException)
                isLocked = false;
            // Could not get a lock for some other reason.
            else
                isLocked = true;
        } finally {
            if (input != null) {
                try {
                    input.close();
                } catch (Exception ex) {
                }
            }
        }
        return isLocked;
    }
}

Related

  1. isBlocking(Channel channel)
  2. isFileLocked(File file)
  3. isLocked(File file)
  4. isLocked(File file)
  5. lock(File file)