当前位置: 移动技术网 > IT编程>开发语言>Java > 5种解决Java独占写文件的方法

5种解决Java独占写文件的方法

2019年07月22日  | 移动技术网IT编程  | 我要评论

本文实例讲解了5种解决java独占写文件的方法,包含自己的一些理解,如若有不妥的地方欢迎大家提出。

方案1:利用randomaccessfile的文件操作选项s,s即表示同步锁方式写

randomaccessfile file = new randomaccessfile(file, "rws");

方案2:利用filechannel的文件锁

file file = new file("test.txt");
fileinputstream fis = new fileinputstream(file);
filechannel channel = fis.getchannel();
filelock filelock = null;
while(true) {
  filelock = channel.trylock(0, long.max_value, false); // true表示是共享锁,false则是独享锁定
  if(filelock!=null) break;
  else  // 有其他线程占据锁
   sleep(1000);
}

方案3:先将要写的内容写入一个临时文件,然后再将临时文件改名(hack方案,利用了缓冲+原子操作的原理)

public class myfile {
  private string filename;
  public myfile(string filename) {
   this.filename = filename;
  }
 
  public synchronized void writedata(string data) throws ioexception {
   string tmpfilename = uuid.randomuuid().tostring()+".tmp";
   file tmpfile = new file(tmpfilename);
   filewriter fw = new filewriter(tmpfile);
   fw.write(data);
   fw.flush();
   fw.close();
 
   // now rename temp file to desired name, this operation is atomic operation under most os
   if(!tmpfile.renameto(filename) {
     // we may want to retry if move fails
     throw new ioexception("move failed");
   }
  }
}

方案4:根据文件路径封装文件,并且用synchronized控制写文件

public class myfile {
  private string filename;
  public myfile(string filename) {
   this.filename = filename;
  } 
  public synchronized void writedata(string data) throws ioexception {
   filewriter fw = new filewriter(filename);
   fw.write(data);
   fw.flush();
   fw.close();
  }     
}

方案5:我自己想出来的一个方案,不太精确。通过切换设置读写权限控制,模拟设置一个可写标记量(蜕变成操作系统中经典的读写问题....)

public class myfile {
  private volatile boolean canwrite = true;
  private string filename;
  public myfile(string filename) {
   this.filename = filename;
  }
  public void writedata(string data) {
   while(!canwrite) {
     try { thread.sleep(100); } catch(interuptedexception ie) { } // 可以设置一个超时写时间
   }
   canwrite = false;
    
   // now write file
 
   canwrite = true;
  }
}

以上就是java独占写文件的解决方法,大家有没有学会,可以参考其他文章进行学习理解。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网