Java NIO - FileLock(文件锁)

Java NIO - FileLock(文件锁) 首页 / Nio入门教程 / Java NIO - FileLock(文件锁)

Java NIO支持并发和多线程,这使它能够同时处理在多个文件上运行的多个线程,但是在某些情况下,无涯教程要求文件不能被任何线程共享并且不可访问。为了满足这种要求,NIO提供了FileLock的API,该API用于提供对整个文件或部分文件的锁定,以使该文件或其部分不会共享或不可访问。

为了提供或应用这种锁,无涯教程必须使用FileChannel或AsynchronousFileChannel,它们为此提供了两个方法 lock()和 tryLock()。两种类型-

  • 排他锁     - 排他锁可防止其他程序获取任一类型的重叠锁。

  • 共享锁     - 共享锁可以防止其他同时运行的程序获取重叠的互斥锁,但允许它们获取重叠的共享锁。

用于获取锁定文件的方法-

  • lock()                                                                                   - FileChannel或AsynchronousFileChannel的此方法获取与给定通道关联的文件的排他锁。

  • lock(long position,long size,boolean shared)       - 此方法是lock方法的重载方法,用于锁定文件的特定部分。

  • tryLock()                                                                             - 如果无法获取该锁,并且尝试获取此通道文件上的显式排他锁,则此方法返回FileLock或null。

  • tryLock(long position,long size,boolean shared)  - 此方法尝试获取此通道文件给定区域上的锁,该锁可以是互斥类型或共享类型。

FileLock类的方法

  • acquiredBy()                                            - 此方法返回获取文件锁定的通道。

  • position()                                                  - 此方法返回锁定区域第一个字节在文件中的位置。

  • size()                                                          - 此方法返回锁定区域的大小(以字节为单位)。

  • isShared()                                                 - 此方法用于确定是否共享锁。

  • overlaps(long position,long size)     - 此方法判断此锁是否与给定的锁范围重叠。

  • isValid()                                                    - 此方法判断所获取的锁是否有效,锁对象在释放之前或关闭关联的文件通道之前一直保持有效以先到者为准。

  • release()                                                     - 释放获得的锁。

  • close()                                                         - 此方法调用release()方法,它已添加到类中,以便可以与自动资源管理块构造结合使用。

FileLock示例。

下面的示例创建文件锁定并向其中写入内容

package com.java.nio;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.channels.FileLock;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
public class FileLockExample {
   public static void main(String[] args) throws IOException {
      String input = "Demo text to be written in locked mode.";  
      System.out.println("Input string to the test file is: " + input);  
      ByteBuffer buf = ByteBuffer.wrap(input.getBytes());  
      String fp = "D:file.txt";  
      Path pt = Paths.get(fp);  
      FileChannel channel = FileChannel.open(pt, StandardOpenOption.WRITE,StandardOpenOption.APPEND);  
      channel.position(channel.size() - 1); //光标在文件末尾的位置
      FileLock lock = channel.lock();   
      System.out.println("The Lock is shared: " + lock.isShared());  
      channel.write(buf);  
      channel.close(); //释放锁
      System.out.println("Content Writing is complete. Therefore close the channel and release the lock.");  
      PrintFileCreated.print(fp);  
   }  
}
package com.java.nio;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class PrintFileCreated {
   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.txt file is: ");  
      while (tr != null) {      
         System.out.println("    " + tr);  
         tr = bufferedreader.readLine();  
      }  
   filereader.close();  
   bufferedreader.close();  
   }  
}

运行上面代码输出

Input string to the test file is: Demo text to be written in locked mode.
The Lock is shared: false
Content Writing is complete. Therefore close the channel and release the lock.
The Content of testout.txt file is: 
To be or not to be?Demo text to be written in locked mode.

祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)

技术教程推荐

Java核心技术面试精讲 -〔杨晓峰〕

持续交付36讲 -〔王潇俊〕

程序员的数学基础课 -〔黄申〕

玩转webpack -〔程柳锋〕

编译原理实战课 -〔宫文学〕

手把手教你玩音乐 -〔邓柯〕

Go 语言项目开发实战 -〔孔令飞〕

手把手带你写一门编程语言 -〔宫文学〕

说透低代码 -〔陈旭〕

好记忆不如烂笔头。留下您的足迹吧 :)