多线程写文件是会有冲突的,会有脏数据,所以我们要给写文件的代码加上锁。
具体流程在以前代码基础上加上锁代码:
FileOutputStream fos = new FileOutputStream(file, true);
FileChannel fc = Channel();
while(true){try{lock = fc.tryLock();}catch (OverlappingFileLockException e){lock = null;}if(lock != null){break;}
}
将上面代码放到写之前就可以。
然后在finally里面
我的整体代码就是
public void writeToFileAppend(String fileName, String outDir, String encode, List<String> data){OutputStreamWriter osr = null;BufferedWriter bw = null;FileLock lock = null;try {File file = new File(outDir, fileName);File out = new File(outDir);if(!ists()){out.mkdirs();}FileOutputStream fos = new FileOutputStream(file, true);FileChannel fc = Channel();while(true){try{lock = fc.tryLock();}catch (OverlappingFileLockException e){lock = null;}if(lock != null){break;}}osr = new OutputStreamWriter(fos, encode);bw = new BufferedWriter(osr);for(int i = 0;i < data.size();i++){bw.(i));bw.newLine();}bw.flush();} catch (IOException e) {e.printStackTrace();}finally {lease();osr.close();bw.close();}catch (Exception e){e.printStackTrace();}}}
本文发布于:2024-02-04 07:50:39,感谢您对本站的认可!
本文链接:https://www.4u4v.net/it/170702372753674.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
留言与评论(共有 0 条评论) |