Several methods of writing files exclusively in Java

From , 5 Years ago, written in Java, viewed 73 times.
URL https://pastebin.vip/view/a3147b88
  1. // 方案1:利用RandomAccessFile的文件操作选项s,s即表示同步锁方式写
  2. RandomAccessFile file = new RandomAccessFile(file, "rws");
  3.  
  4. // 方案2:利用FileChannel的文件锁
  5. File file = new File("test.txt");
  6. FileChannel channel = fis.getChannel();
  7. FileLock fileLock = null;
  8. while(true) {
  9.    fileLock = channel.tryLock(0, Long.MAX_VALUE, false);  // true表示是共享锁,false则是独享锁定
  10.    if(fileLock!=null) break;
  11.    else   // 有其他线程占据锁
  12.       sleep(1000);
  13. }
  14.  
  15. // 方案3:先将要写的内容写入一个临时文件,然后再将临时文件改名(Hack方案,利用了缓冲+原子操作的原理)
  16. public class MyFile {
  17.    private String fileName;
  18.    public MyFile(String fileName) {
  19.       this.fileName = fileName;
  20.    }
  21.  
  22.    public synchronized void writeData(String data) throws IOException {
  23.       String tmpFileName = UUID.randomUUID().toString()+".tmp";
  24.       File tmpFile = new File(tmpFileName);
  25.       FileWriter fw = new FileWriter(tmpFile);
  26.       fw.write(data);
  27.       fw.flush();
  28.       fw.close();
  29.  
  30.       // now rename temp file to desired name, this operation is  atomic operation under most os
  31.       if(!tmpFile.renameTo(fileName) {
  32.          // we may want to retry if move fails
  33.          throw new IOException("Move failed");
  34.       }
  35.    }
  36. }
  37.  
  38. // 方案4:根据文件路径封装文件,并且用synchronized控制写文件
  39. public class MyFile {
  40.    private String fileName;
  41.    public MyFile(String fileName) {
  42.       this.fileName = fileName;
  43.    }
  44.    public synchronized void writeData(String data) throws IOException {
  45.       FileWriter fw = new FileWriter(fileName);
  46.       fw.write(data);
  47.       fw.flush();
  48.       fw.close();
  49.    }        
  50. }
  51.  
  52. // 方案5:我自己想出来的一个方案,不太精确。通过切换设置读写权限控制,模拟设置一个可写标记量(蜕变成操作系统中的读写问题....)
  53. public class MyFile {
  54.    private boolean canWrite = false;
  55.    private String fileName;
  56.    public MyFile(String fileName) {
  57.       this.fileName = fileName;
  58.    }
  59.    public void writeData(String data) {
  60.       while(!canWrite) {
  61.           try { Thread.sleep(100); } catch(InteruptedException ie) { // }  // 可以设置一个超时写时间
  62.       }
  63.       canWrite = false;
  64.      
  65.       // Now write file
  66.    }
  67. }
  68. //java/6243

Reply to "Several methods of writing files exclusively in Java"

Here you can reply to the paste above

captcha

https://burned.cc - Burn After Reading Website