4

我的问题是:我正在使用 aWatchService来获取有关特定文件夹中新文件的通知,现在如果文件在所述文件夹中被移动/复制或创建,则会触发事件并返回新文件的名称。现在的问题是,如果我尝试访问该文件并且它还没有完全存在(例如,副本仍在进行中),则会引发异常。我试图做这样的事情:

RandomAccessFile raf = new RandomAccessFile(fileName, "rw");
FileChannel fc = raf.getChannel();
FileLock lck = fc.lock();

但是即使获得了锁,如果我尝试写入文件,有时仍然会引发异常,因为另一个进程仍然有一个打开的句柄。

现在,如何才能锁定 Java 中的文件以实现真正的独占访问?

4

2 回答 2

3

对我来说,声明

RandomAccessFile raf = new RandomAccessFile(fileName, "rw"); 

如果我无法获得对文件的锁定,则返回 FileNotFoundException。我捕获了 filenotfound 异常并对其进行了处理...

public static boolean isFileLocked(String filename) {
    boolean isLocked=false;
    RandomAccessFile fos=null;
    try {
        File file = new File(filename);
        if(file.exists()) {
            fos=new RandomAccessFile(file,"rw");
        }
    } catch (FileNotFoundException e) {
        isLocked=true;
    }catch (Exception e) {
        // handle exception
    }finally {
        try {
            if(fos!=null) {
                fos.close();
            }
        }catch(Exception e) {
            //handle exception
        }
    }
    return isLocked;
}

您可以循环运行它并等到您锁定文件。线不行吗

FileChannel fc = raf.getChannel();

如果文件被锁定,永远无法到达?你会得到一个 FileNotFoundException 抛出..

于 2011-12-30T10:24:53.260 回答
0

最好不要使用 java.io 包中的类,而是使用 java.nio 包。后者有一个 FileLock 类,可用于锁定 FileChannel。

try {
        // Get a file channel for the file
        File file = new File("filename");
        FileChannel channel = new RandomAccessFile(file, "rw").getChannel();

        // Use the file channel to create a lock on the file.
        // This method blocks until it can retrieve the lock.
        FileLock lock = channel.lock();

        /*
           use channel.lock OR channel.tryLock();
        */

        // Try acquiring the lock without blocking. This method returns
        // null or throws an exception if the file is already locked.
        try {
            lock = channel.tryLock();
        } catch (OverlappingFileLockException e) {
            // File is already locked in this thread or virtual machine
        }

        // Release the lock - if it is not null!
        if( lock != null ) {
            lock.release();
        }

        // Close the file
        channel.close();
    } catch (Exception e) {
    }
于 2020-11-22T05:50:31.383 回答