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.zaixian;

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.zaixian;

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 xuhuhu.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 xuhuhu.com

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

上一篇: Java NIO编码和解码 下一篇: Java NIO时间服务器示例