多线程写文件是会有冲突的,会有脏数据,所以我们要给写文件的代码加上锁。
具体流程在以前代码基础上加上锁代码:
FileOutputStream fos = new FileOutputStream(file, true);
FileChannel fc = fos.getChannel();
while(true){
try{
lock = fc.tryLock();
}catch (OverlappingFileLockException e){
lock = null;
}
if(lock != null){
break;
}
}
将上面代码放到写之前就可以。
然后在finally里面
lock.release();
我的整体代码就是
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(!out.exists()){
out.mkdirs();
}
FileOutputStream fos = new FileOutputStream(file, true);
FileChannel fc = fos.getChannel();
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.write(data.get(i));
bw.newLine();
}
bw.flush();
} catch (IOException e) {
e.printStackTrace();
}finally {
try{
lock.release();
osr.close();
bw.close();
}catch (Exception e){
e.printStackTrace();
}
}
}