带序列化的OptionalDataException

时间:2014-05-14 18:00:34

标签: java serialization io objectinputstream

我遇到了序列化包含bufferedImage和枚举实例的对象的问题,更具体地说是使用OptionalDataException。我已经尝试整天识别错误,但我无法确定错误并感谢您的帮助。

它将对象写得很好,但在阅读时我会遇到异常。文档定义了异常,因为我在流中有备用的原始数据,但我无法弄清楚原因,地点或方式。

代码:

private void writeObject(ObjectOutputStream out) throws IOException {

    out.defaultWriteObject();
    ImageIO.write(preview, "png", out);
    ImageIO.write(thumbnail, "png", out);
    ImageIO.write(original, "png", out);

    out.writeInt(tags.size());
    for (String string : tags) {
        out.writeObject(string);
    }

    out.writeInt(versions.size());
    for (Entry<FiltersEnum, BufferedImage> entry : versions.entrySet()) {
        out.writeObject(entry.getKey().name());
        ImageIO.write(entry.getValue(), "png", out);
    }

}

private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException {
    in.defaultReadObject();
    preview = ImageIO.read(in);
    thumbnail = ImageIO.read(in);
    original = ImageIO.read(in);

    tags = new TreeSet<String>();
    int len = in.readInt();
    for (int i = 0; i < len; i++) {
    tags.add((String) in.readObject());
    }

    versions = new TreeMap<FiltersEnum, BufferedImage>();
    len = in.readInt();
    try {
    for (int i = 0; i < len; i++) {
            FiltersEnum key = FiltersEnum.valueOf((String) in.readObject());
        versions.put(key, ImageIO.read(in));
        }
    } catch (OptionalDataException e) {
        e.printStackTrace();
    }
}

来自:

imageList.add((ExtendedImage) in.readObject());

跟踪:

java.io.OptionalDataException
at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1302)
at java.io.ObjectInputStream.readObject(ObjectInputStream.java:370)
at model.ExtendedImage.readObject(ExtendedImage.java:214)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at java.io.ObjectStreamClass.invokeReadObject(ObjectStreamClass.java:1017)
at java.io.ObjectInputStream.readSerialData(ObjectInputStream.java:1891)
at java.io.ObjectInputStream.readOrdinaryObject(ObjectInputStream.java:1796)
at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1348)
at java.io.ObjectInputStream.readObject(ObjectInputStream.java:370)
at model.Library.loadFromHiddenDirectory(Library.java:145)
at model.Model.<init>(Model.java:36)
at controller.Controller.<init>(Controller.java:39)
at general.DesktopHipster.<init>(DesktopHipster.java:18)
at general.DesktopHipster.main(DesktopHipster.java:26)

0 个答案:

没有答案