Java FileLock lockFile(File file)

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

Description

Locks a file for the current JVM.

License

Open Source License

Parameter

Parameter Description
file a parameter

Return

a FileLock object, or null if file could not be locked

Declaration

public static FileLock lockFile(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.FileOutputStream;

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

public class Main {
    /**/*from  w w  w .jav a 2 s.  c  o m*/
     * Locks a file for the current JVM. Will create the file if it does not
     * exist
     * 
     * @param file
     * @return a FileLock object, or null if file could not be locked
     */
    public static FileLock lockFile(File file) {
        FileOutputStream input = null;
        FileLock lock = null;
        try {
            input = new FileOutputStream(file);
            FileChannel fileChannel = input.getChannel();
            lock = fileChannel.tryLock();

            if (lock.isValid())
                return lock;
        } catch (Exception e) {
            // Could not get a lock for some reason.
            return null;
        } finally {
            try {
                if (input != null && (lock == null || !lock.isValid())) {
                    input.close();
                }
            } catch (Exception ex) {
            }
        }
        return null;
    }
}

Related

  1. isFileLocked(File file)
  2. isFileLocked(File file)
  3. isLocked(File file)
  4. isLocked(File file)
  5. lock(File file)
  6. lockFile(File file, RandomAccessFile raf)
  7. lockFileExists(File file)
  8. openTcpSocket(boolean blocking)
  9. pauseForLock(File f, int frequency, int totalTime)