如何读取序列化文件?

时间:2015-04-15 02:16:38

标签: java file serializable

这在Java中也是如此。我似乎无法使用此方法,保存部分工作得很好并保存对象。但是一旦我尝试读取文件它就不起作用,我得到ObjectInputStream错误。我是新手使用Serializable界面,其他任何问题似乎都没有帮助我。预期输出为name Joe, weight 153, height 69。错误是:

java.io.InvalidClassException:Person;本地类不兼容:stream classdesc serialVersionUID = -1404541419531259795,本地类serialVersionUID = 3020781085877336930     at java.io.ObjectStreamClass.initNonProxy(Unknown Source)     at java.io.ObjectInputStream.readNonProxyDesc(Unknown Source)     at java.io.ObjectInputStream.readClassDesc(Unknown Source)     at java.io.ObjectInputStream.readOrdinaryObject(Unknown Source)     at java.io.ObjectInputStream.readObject0(Unknown Source)     在java.io.ObjectInputStream.readObject(未知来源)

    public static boolean save(Person p, String filename) {
        try {
        ObjectOutputStream os = new ObjectOutputStream(
                new FileOutputStream(filename));
        os.writeObject(p);
        os.close();
        return true;
    } catch (Exception e) {
        e.printStackTrace();
    }
    return false;
}

    public static Person read(String filename) {
    try {
        ObjectInputStream oi = new ObjectInputStream(new FileInputStream(
                filename));
        Object o = oi.readObject();
        oi.close();
        if (o instanceof Person)
            return (Person) o;
    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}

public static void main(String[] args) {
    Scanner s = new Scanner(System.in);
    System.out.println("Do you want to save or load?");
    String option = s.next();
    Person p = new Person("Joe", 154, 69);
    if (option.equals("save")) {
        if (save(p, "newfile")) {
            System.out.println("Saved.");
        }
    }
    if (option.equals("load")) {
        Person p1 = read("newfile");
        if ((p1 != null)) {
            System.out.println(p1.getInfo());
        }
    }

}

}

1 个答案:

答案 0 :(得分:1)

serialVersionUID 引入类,如What is a serialVersionUID and why should I use it?

中所述

似乎您已经以某种方式更改了Person类,现在您无法读取已保存的版本,因为字节码已被更改。