今天在学习Java的文件输入输出时,学习了高级流ObjectInputStream,它使用了是序列化的写入和写出,在写出的时候遇到了一个错误:java.io.InvalidClassException:local class incompatible: stream classdesc serialVersionUID = …, local class serialVersionUID = …
在网上找了一些solution,解决办法如下:在实现serializable接口的类中,定义一个serialVersionUID变量,类型为public static final long,以我的为例:
public final static long serialVersionUID = -8497580858753153590l;
具体的作用我是参考的这一篇文章,May it helpful! http://swiftlet.net/archives/1268
下面提一下代码:
1 import java.io.Serializable; 2 import java.util.List; 3 4 public class Person implements Serializable{ 5 private String name; 6 private int age; 7 private char sex; 8 private List<String> list; 9 public final static long serialVersionUID = -8497580858753153590l; 10 11 Person(String name,int age,char sex,List<String> list){ 12 this.name = name; 13 this.age = age; 14 this.sex = sex; 15 this.list = list; 16 } 17 public String toString(){ 18 return name+" "+age+" "+sex+" "+list; 19 } 20 21 }
上面是构造的一个辅助类,下面是流的实例类。
1 import java.io.FileInputStream; 2 import java.io.FileNotFoundException; 3 import java.io.IOException; 4 import java.io.ObjectInputStream; 5 public class OIS { 6 7 public static void main(String[] args) throws IOException, ClassNotFoundException { 8 // TODO Auto-generated method stub 9 FileInputStream fis = new FileInputStream("person.obj"); 10 ObjectInputStream ois = new ObjectInputStream(fis); 11 Person per = (Person)ois.readObject(); 12 13 System.out.println(per); 14 ois.close(); 15 16 } 17 18 }