欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

java 文件锁的简单实现

程序员文章站 2023-11-12 19:39:40
java  文件锁的简单实现            ...

java  文件锁的简单实现

             java文件锁的功能,隐私文件及安全性的提升,实现起来不难,这里贴下实现代码:

 实例代码:

import java.io.file; 
import java.io.fileinputstream; 
import java.io.filenotfoundexception; 
import java.io.ioexception; 
import java.io.inputstreamreader; 
import java.io.randomaccessfile; 
import java.nio.channels.filechannel; 
import java.nio.channels.filelock; 
public class filelocker { 
  public static void main(string[] args) throws ioexception { 
    file f = new file("aaa.txt"); 
    system.out.println(getfilecontent(f) + 1);// no lock 
    filelock lock = getfilelock(f);// lock 
    system.out.println(getfilecontent(f) + 2); 
    lock.release();// lock release 
    system.out.println(getfilecontent(f) + 3);// no lock 
  } 
  /** 
   * get file content. 
   * 
   * @param file 
   * @return 
   */ 
  public static string getfilecontent(file file) { 
    string line = ""; 
    string content = ""; 
    try { 
      bufferedreader bf = new bufferedreader(new inputstreamreader( 
          new fileinputstream(file))); 
      while ((line = bf.readline()) != null) { 
        content += line; 
      } 
    } catch (filenotfoundexception e) { 
      content = "error "; 
    } catch (ioexception e) { 
      content = "error "; 
    } 
    return content; 
  } 
  /** 
   * get lock. 
   * 
   * @param file 
   * @return 
   * @throws ioexception 
   */ 
  public static filelock getfilelock(file file) throws ioexception { 
    randomaccessfile fi = new randomaccessfile(file, "rw"); 
    filechannel fc = fi.getchannel(); 
    return fc.trylock(); 
  } 
} 

感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!