Java NIO通道FileLock


FileLock鎖定或嘗試鎖定檔案的給定部分。它屬於java.nio.channels包,該功能在JDK 1.4以上版本可用。

FileLock用於在共用模式或非共用模式下鎖定檔案。它有兩個重要的方法如下:

  • FileLock.lock(long position, long size, boolean shared)
  • FileLock.tryLock(long position, long size, boolean shared)

上述方法使用引數作為初始位置,檔案大小鎖定和一個引數來決定是否共用鎖定。

建立檔案鎖

當使用FileChannelAsynchronousFileChannellock()tryLock()方法之一獲取檔案鎖時,將建立檔案鎖定物件。

基本FileLock範例

下面來看看使用專用鎖定的通道在檔案中寫入(附加)的程式(FileLockExample.java):

package com.yiibai;

import java.io.IOException;
import java.nio.channels.FileChannel;
import java.nio.channels.FileLock;
import java.nio.ByteBuffer;
import java.nio.file.Paths;
import java.nio.file.Path;
import java.nio.file.StandardOpenOption;

public class FileLockExample {
    public static void main (String [] args)  
            throws IOException {  
        String input = "* end of the file.";  
        System.out.println("Input string to the test file is: " + input);  
        ByteBuffer buf = ByteBuffer.wrap(input.getBytes());  
        String fp = "testout-file.txt";  
        Path pt = Paths.get(fp);  
        FileChannel fc = FileChannel.open(pt, StandardOpenOption.WRITE,  
StandardOpenOption.APPEND);  
        System.out.println("File channel is open for write and Acquiring lock...");  
        fc.position(fc.size() - 1); // position of a cursor at the end of file       
        FileLock lock = fc.lock();   
        System.out.println("The Lock is shared: " + lock.isShared());  
        fc.write(buf);  
        fc.close(); // Releases the Lock  
        System.out.println("Content Writing is complete. Therefore close the channel and release the lock.");  
        PrintFile.print(fp);  
    }
}

PrintFile.java檔案的內容如下 -

package com.yiibai;

import java.io.IOException;
import java.io.FileReader;
import java.io.BufferedReader;

public class PrintFile {
    public static void print(String path) throws IOException {
        FileReader filereader = new FileReader(path);
        BufferedReader bufferedreader = new BufferedReader(filereader);
        String tr = bufferedreader.readLine();
        System.out.println("The Content of testout-file.txt file is: ");
        while (tr != null) {
            System.out.println("    " + tr);
            tr = bufferedreader.readLine();
        }
        filereader.close();
        bufferedreader.close();
    }
}

注意:在執行程式碼之前,需要建立一個名稱為「testout-file.txt」的文字檔案,文字檔案的內容如下:

Welcome to tw511.com

This is the example of FileLock in Java NIO channel.

執行上面範例程式碼,得到以下結果 -

Input string to the test file is: * end of the file.
File channel is open for write and Acquiring lock...
The Lock is shared: false
Content Writing is complete. Therefore close the channel and release the lock.
The Content of testout-file.txt file is: 
    Welcome to tw511.com

    This is the example of FileLock in Java NIO channel.* end of the file.