Java FileLock lock(File file)

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

Description

lock

License

Apache License

Declaration

public static FileOutputStream lock(File file) 

Method Source Code

//package com.java2s;
/**/*  w ww.ja  v a 2 s.c  o  m*/
 * Copyright (C) 2008 http://code.google.com/p/maven-license-plugin/
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *         http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import java.io.*;

import java.nio.channels.FileLock;
import java.util.HashMap;

import java.util.Map;

public class Main {
    private static final Map<File, FileLock> locks = new HashMap<File, FileLock>();

    public static FileOutputStream lock(File file) {
        try {
            FileOutputStream out = new FileOutputStream(file);
            FileLock lock = out.getChannel().tryLock();
            if (lock == null) {
                throw new IllegalStateException("Cannot acquire a lock on file " + file
                        + ". Please verify that this file is not used by another process.");
            }
            locks.put(file, lock);
            return out;
        } catch (IOException e) {
            throw new IllegalStateException("An I/O error occured when trying to get a lock on file " + file
                    + ". Please verify that this file is not used by another process. Cause: " + e.getMessage(), e);
        }
    }
}

Related

  1. isBlocking(Channel channel)
  2. isFileLocked(File file)
  3. isFileLocked(File file)
  4. isLocked(File file)
  5. isLocked(File file)
  6. lockFile(File file)
  7. lockFile(File file, RandomAccessFile raf)
  8. lockFileExists(File file)
  9. openTcpSocket(boolean blocking)