源码网商城,靠谱的源码在线交易网站 我的订单 购物车 帮助

源码网商城

java 文件锁的简单实现

  • 时间:2021-10-12 16:13 编辑: 来源: 阅读:
  • 扫一扫,手机访问
摘要:java 文件锁的简单实现
[b]java  文件锁的简单实现[/b] [b]             java文件锁的功能,隐私文件及安全性的提升,实现起来不难,这里贴下实现代码:[/b] [b] 实例代码:[/b]
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(); 
  } 
} 

感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!
  • 全部评论(0)
联系客服
客服电话:
400-000-3129
微信版

扫一扫进微信版
返回顶部