public void Test2(){
ObjectInputStream o=null;
Person p4;
try {
o=new ObjectInputStream(new FileInputStream("liuliu.txt"));
Object oo=o.readObject();
p4=(Person)o.readObject();
System.out.println( p4);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally{
try {
o.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}下面是出现错误的原因
java.io.EOFException
at java.io.ObjectInputStream$BlockDataInputStream.peekByte(Unknown Source)
at java.io.ObjectInputStream.readObject0(Unknown Source)
at java.io.ObjectInputStream.readObject(Unknown Source)
at 对象序列化和反序列化.Test2(对象序列化和反序列化.java:41)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
ObjectInputStream o=null;
Person p4;
try {
o=new ObjectInputStream(new FileInputStream("liuliu.txt"));
Object oo=o.readObject();
p4=(Person)o.readObject();
System.out.println( p4);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally{
try {
o.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}下面是出现错误的原因
java.io.EOFException
at java.io.ObjectInputStream$BlockDataInputStream.peekByte(Unknown Source)
at java.io.ObjectInputStream.readObject0(Unknown Source)
at java.io.ObjectInputStream.readObject(Unknown Source)
at 对象序列化和反序列化.Test2(对象序列化和反序列化.java:41)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
p4=(Person)o.readObject();已经读入到oo, 为何再次读入?
其实我挺好奇你的liuliu.txt里面存了什么,这样读出来强转能正确的转化么
一般只有用ObjectOutputStream输出的序列化对象才能被这种方式读取
File file = new File("D:/momo.txt");
FileOutputStream fileOutputStream = new FileOutputStream(file);
ObjectOutputStream objectOutputStream = new ObjectOutputStream(
fileOutputStream);
Person person = new Person("zhangsan");
Person person2 = new Person("lisi");
Person person3 = new Person("wangwu");
objectOutputStream.writeObject(person);
objectOutputStream.writeObject(person2);
objectOutputStream.writeObject(person3);
objectOutputStream.writeObject(null);
objectOutputStream.close();
fileOutputStream.close();
注意最后写入一个空对象。第7行 修改为 p4=(Person)oo;
就能正确读到;