集册 Java实例教程 锁定通道的文件

锁定通道的文件

—— 锁定频道的文件

欢马劈雪     最近更新时间:2020-01-02 10:19:05

594
锁定频道的文件

import java.io.IOException;//来 自 时代Java - N o w  J a v a . c o m

import java.nio.ByteBuffer;

import java.nio.channels.FileChannel;

import java.nio.channels.FileLock;

import java.nio.channels.OverlappingFileLockException;

import java.nio.file.Path;

import java.nio.file.Paths;

import java.nio.file.StandardOpenOption;

import java.util.EnumSet;


public class Main {

  public static void main(String[] args) throws Exception{

    Path path = Paths.get("C:/folder1/email", "test.txt");

    ByteBuffer buffer = ByteBuffer.wrap("test test".getBytes());

    try (FileChannel fileChannel = (FileChannel.open(path,

        EnumSet.of(StandardOpenOption.READ, StandardOpenOption.WRITE)))) {

      FileLock lock = fileChannel.lock();

      lock = fileChannel.tryLock();

      if (lock.isValid()) {

        System.out.println("Writing to a locked file ...");/**from N o w  J a v a  .   c o m**/

        Thread.sleep(60000);

        fileChannel.position(0);

   
展开阅读全文