今天学习对象序列化的时候,自己每次写入同一个文件,读取的时候只能读到第一次写入的Object,读取后面写入的Object都会报java.io.StreamCorruptedException错误,经过搜索,发现每次写入对象的时候,Java默认的对象序列化都会在每次写入前写入一个四个字节的头。因此,在对象追加的时候就需要把头去掉。代码如下:
import java.io.EOFException;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
public class Test {
public static void main(String[] args) throws EOFException{
Person per = new Person();
per.setName("ysj");
per.setAge(23);
ObjectInputStream in = null;
ObjectOutputStream out = null;
FileOutputStream ostream = null;
try {
File file = new File("persons.txt");
if( file.exists() ){
ostream = new FileOutputStream(file,true);
out = new ObjectOutputStream(ostream);
long pos = ostream.getChannel().position() - 4;
ostream.getChannel().truncate(pos);
}else{
file.createNewFile();
ostream = new FileOutputStream(file);
out = new ObjectOutputStream(ostream);
}
out.writeObject(per);
in = new ObjectInputStream(
new FileInputStream("persons.txt"));
while( true ){
Person p = (Person) in.readObject();
System.out.println(p.getName() + ":" + p.getAge());
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (IOException e){
if( e instanceof EOFException ){
System.out.println("对象读取完毕!");
}else{
e.printStackTrace();
}
} finally{
if( out != null ){
try{
out.close();
}catch(IOException e){
e.printStackTrace();
}
out = null;
}
if( ostream != null ){
try{
ostream.close();
}catch(IOException e){
e.printStackTrace();
}
ostream = null;
}
if( in != null ){
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
in = null;
}
}
}
}