簡體   English   中英

Java - 鎖定文件以進行獨占訪問

[英]Java - locking a file for exclusive access

我的問題是這樣的:我正在使用WatchService來獲取有關特定文件夾中新文件的通知,現在如果在所述文件夾中移動/復制或創建文件,則會觸發事件並返回新文件的名稱。 現在的問題是,如果我嘗試訪問該文件但它尚未完全存在(例如復制仍在進行中),則會引發異常。 我試過的是做這樣的事情:

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

但是,即使獲得了鎖,如果我嘗試寫入文件,有時仍然會引發異常,因為另一個進程仍然有一個打開的句柄。

現在,如何鎖定 Java 中的文件以進行真正的獨占訪問?

對我來說,聲明

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 拋出..

最好不要使用 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) {
    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM