读书人

quot;main quot; java.io.StreamCorruptedExc

发布时间: 2011-11-25 21:31:10 作者: rapoo

关于对象存储的小问题.
代码:
package src;
import java.io.*;

public class TestObjectStreamAppend {

public static void main(String[] args) throws Exception{
Teacher t=new Teacher( "hlonger ");
Student s1=new Student( "zhijunzhang ",30,99.0,t);
Student s2=new Student( "keep ",30,98.999,t);

FileOutputStream fos=new FileOutputStream( "student.dat ");
//存在覆盖,不存在建立.
ObjectOutputStream oos=new ObjectOutputStream(fos);

oos.writeObject(s1);
oos.close();

fos=new FileOutputStream( "student.dat ",true);
//true代表append

oos=new ObjectOutputStream(fos);
oos.writeObject(s2);
oos.close();

FileInputStream fis=new FileInputStream( "student.dat ");
ObjectInputStream ois=new ObjectInputStream(fis);
Object o;

try{
while(true){
o=ois.readObject();
System.out.println(o);
}
}catch(EOFException ee){
}
ois.close();
}
}

运行结果:
Student 's Name:zhijunzhang Age:30 Mark:99.0 Teacher:hlonger
Exception in thread "main " java.io.StreamCorruptedException: invalid type code: AC
at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1356)
at java.io.ObjectInputStream.readObject(ObjectInputStream.java:351)
at src.TestObjectStreamAppend.main(TestObjectStreamAppend.java:28)

我的目的是在存储一个对象后(关闭流),加入一个对象(append)
可是输入怎么少一个,还有异常跑出,请问这问题 出在那里?

[解决办法]
你把 一个流写两个对象 与两个流写两个对象 后得到的student.dat

比较一下 就知道了

两个文件 的差别在于 后者 多了AC ED四个字节

反序列化的时候肯定报错了


读书人网 >J2SE开发

热点推荐