文件的加锁解锁

来源:互联网 发布:口红推荐 知乎 编辑:程序博客网 时间:2024/04/27 04:31

import java.io.FileOutputStream;
import java.nio.channels.*;

public class FileLocking
 {

  /**
   * @param args
   */
  public static void main(String[] args) throws Exception
   {
    // TODO 自动生成方法存根
    FileOutputStream fos = new FileOutputStream("file.txt");
    FileLock fl = fos.getChannel().tryLock();
    if (fl != null)
     {
      if (fl.isShared()) System.out.println("File is locked by a Shared Lock!");
       else System.out.println("File is locked by a Single Lock!");
      Thread.sleep(100);
      fl.release();
      System.out.println("File is unlocked!");
     }
    fos.close();
   }
 } 

原创粉丝点击