本帖最后由 寇龙飞 于 2012-8-24 21:22 编辑
你应该看了老毕讲的IO对象序列化
先贴两个类的代码
这个问题演示的步骤文字表达起来比较繁琐,不明原理的话看着很容易晕。建议你最好去看着老毕的视频思考下。- package com.itheima.test;
- import java.io.FileInputStream;
- import java.io.FileOutputStream;
- import java.io.ObjectInputStream;
- import java.io.ObjectOutputStream;
- public class ObjectStreamTest {
- public static void main(String[] args) throws Exception {
- //writeObj();
- readObj();
- }
-
- public static void readObj() throws Exception {
-
- ObjectInputStream ois = new ObjectInputStream(
- new FileInputStream("MyPerson.object"));
-
- MyPerson p = (MyPerson)ois.readObject();
- System.out.println(p);
-
- ois.close();
- }
-
- public static void writeObj() throws Exception {
-
- ObjectOutputStream oos = new ObjectOutputStream(
- new FileOutputStream("MyPerson.object"));
-
- oos.writeObject(new MyPerson("zhangsan", 29));
-
- oos.close();
- }
- }
复制代码- package com.itheima.test;
- import java.io.Serializable;
- class MyPerson implements Serializable {
- /**
- *
- */
- private static final long serialVersionUID = -6527801543108636145L;
- /**
- *
- */
- //private static final long serialVersionUID = 1L;
-
- private String name;
- public int age;
-
- public MyPerson(String name, int age) {
- super();
- this.name = name;
- this.age = age;
- }
- public String getName() {
- return name;
- }
- public void setName(String name) {
- this.name = name;
- }
- public int getAge() {
- return age;
- }
- public void setAge(int age) {
- this.age = age;
- }
- @Override
- public String toString() {
- return "MyPerson [name=" + name + ", age=" + age + "]";
- }
- }
复制代码 运行结果:- MyPerson [name=zhangsan, age=29]
复制代码 我把MyPerson类的属性name的权限修改为privat后,运行,报错结果为:- Exception in thread "main" java.io.InvalidClassException: com.itheima.test.MyPerson; local class incompatible: stream classdesc serialVersionUID = 6549094864754487897, local class serialVersionUID = -6527801543108636145
- at java.io.ObjectStreamClass.initNonProxy(ObjectStreamClass.java:604)
- at java.io.ObjectInputStream.readNonProxyDesc(ObjectInputStream.java:1601)
- at java.io.ObjectInputStream.readClassDesc(ObjectInputStream.java:1514)
- at java.io.ObjectInputStream.readOrdinaryObject(ObjectInputStream.java:1750)
- at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1347)
- at java.io.ObjectInputStream.readObject(ObjectInputStream.java:369)
- at com.itheima.test.ObjectStreamTest.readObj(ObjectStreamTest.java:20)
- at com.itheima.test.ObjectStreamTest.main(ObjectStreamTest.java:12)
复制代码 太长了,先发了,下个楼层来回答你的几个疑问。 |