所以我想拥有一个可以将bufferedWriter作为字段保存的类,该字段可以保存bufferedWriter对象的值,该值将由某个函数一次又一次地写入,直到完成所有需要的写入为止, 但是我得到的文件的值已损坏,只有结尾字符长度正确地写入了文件。
好像我缺少关于fileWriter的关键概念。
如果我用与写入相同的方法关闭bufferedWriter,则效果很好。
公共类TxtFileHelperImpl {
private File someFile;
private BufferedOutputStream bufferedOutputStream;
public TxtFileHelperImpl(String repoPath, String fileName){
this.someFile = new File(FilenameUtils.concat(repoPath,fileName));
}
public boolean writeToFile(List<String> stringList){
try {
this.bufferedOutputStream = Optional.ofNullable(this.bufferedOutputStream)
.orElse(new BufferedOutputStream(new FileOutputStream(this.someFile)));
}catch (FileNotFoundException e) {
log.error("#error creating outputStream from file e:{}",e);
return false;
}
try {
for(String stringToWrite:stringList){
bufferedOutputStream.write(stringToWrite.getBytes());
}
}catch (IOException e){
log.error("#error writing to file e:{}",e);
return false;
}
return true;
}
public Single<Boolean> closeFile(){
return Single.fromCallable(()->{
if(this.bufferedOutputStream==null){
return false;
}
this.bufferedOutputStream.flush();
this.bufferedOutputStream.close();
return true;
}).doOnError((throwable)->{log.error("#some error happened while writing to file ,e:{}",throwable); Single.just(false);});
}
public File getFile(){
return this.someFile;
}
bufferedWriter对象不能作为字段保存吗? 实现此目的的替代方法是什么?