用ObjectOutputStream写到文件时,会调用writeStreamHeader的方法,在写入你要写入的内容之前会先写入一个header,这样才会在读出的时候解析出来。但是如果用了FileOutputStream追加的方法,就会导致每次追加的时候都会写入那个header,而读的时候只需要第一个header,所以就会把后面的header当做是你写的Object的一部分,这样就导致了无法解析而出现异常。针对这个问题,原作者进行了一些改进,写了自己的
import java.io.File;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
public class AppendableObjectOutputStream extends ObjectOutputStream {
private static File file;
private AppendableObjectOutputStream(OutputStream out,File file) throws IOException {
super(out);
}
public static AppendableObjectOutputStream getInstance(OutputStream out,File f) throws IOException{//这个方法主要是解决file的传入问题
file=f;
return new AppendableObjectOutputStream(out,f);
}
@Override
protected void writeStreamHeader() throws IOException {
if(!file.exists()||(file.exists()&&file.length()==0)){
super.writeStreamHeader();
}
}
}
我想可以单独写个write()与read()方法,当写的时候用List来存储要写入的数据,再循环写入。
import java.io.File;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
public class AppendableObjectOutputStream extends ObjectOutputStream {
private static File file;
private AppendableObjectOutputStream(OutputStream out,File file) throws IOException {
super(out);
}
public static AppendableObjectOutputStream getInstance(OutputStream out,File f) throws IOException{//这个方法主要是解决file的传入问题
file=f;
return new AppendableObjectOutputStream(out,f);
}
@Override
protected void writeStreamHeader() throws IOException {
if(!file.exists()||(file.exists()&&file.length()==0)){
super.writeStreamHeader();
}
}
}
我想可以单独写个write()与read()方法,当写的时候用List来存储要写入的数据,再循环写入。