怎样在不同线程间实现对文件的同步操作
采用了一个核心类:org.apache.commons.io.output.LockableFileWriter
该类在实例化的时候会在临时文件夹创建一个lock文件,close的时候删除该lock文件。
根据这个lock的存在与否来判断目标文件是否被锁定。
如果目标文件使用中,那么创建lock文件会抛出异常。
拿锁的代码:
//如果文件被锁,那么就持续的尝试拿锁60秒 LockableFileWriter writer = null; int step = 0; while(null == writer && step < 60){ try { writer = new LockableFileWriter(file); } catch (IOException e) { try { this.wait(1000); } catch (InterruptedException e1) { logger.error(e1); } step++; } } if(null == writer){ return; } 释放锁的代码 try { writer.close(); } catch (IOException e) { logger.error(" 释放锁出错", e); } 如果不想打开文件,但是又想锁定文件,不让LockableFileWriter 用。那么只好直接操作那个lock文件了。 //拿锁String destFile = xxxxx.txt;File lockFile = null; boolean isLockCreated = false; int step = 0; while(isLockCreated == false && step < 60){ String lock = System.getProperty("java.io.tmpdir") + "/" + destFile + ".lck"; lockFile = new File(lock); try { isLockCreated = lockFile.createNewFile(); if(!isLockCreated){ try { this.wait(1000); } catch (InterruptedException e) { logger.error(e); } } } catch (IOException e) { try { this.wait(1000); } catch (InterruptedException e1) { logger.error(e1); } logger.error(e); } step++; } if(false == isLockCreated || null == lockFile){ return; }/*业务操作*///放锁lockFile.deleteOnExit();