集册 Java实例教程 在文件上创建文件锁

在文件上创建文件锁

欢马劈雪     最近更新时间:2020-01-02 10:19:05

544
在文件上创建文件锁

import java.io.File;/** 时 代 J a v a 提 供 **/

import java.io.RandomAccessFile;

import java.nio.channels.FileChannel;

import java.nio.channels.FileLock;

import java.nio.channels.OverlappingFileLockException;


public class Main {


  public void main(String[] argv) {

    try {

      File file = new File("filename");

      FileChannel channel = new RandomAccessFile(file, "rw").getChannel();


      // Use the file channel to create a lock on the file.

      // blocks until it can retrieve the lock./* 来 自 时代Java*/

      FileLock lock = channel.lock();


      // Try acquiring the lock without blocking. returns

      // null or throws an exception if the file is already locked.

      try {

        lock = channel.tryLock();

      } catch (
展开阅读全文