package com.n;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;

public class S implements Serializable {

    private static final long serialVersionUID = 1L;

    transient int i;

    public static void main(String[] args) throws Exception, IOException {

        ObjectOutputStream oos =
             new ObjectOutputStream(new FileOutputStream("c:\\jav\\f.txt"));

        S obj1 = new S(10);
        oos.writeInt(obj1.i);
        oos.writeObject(obj1);

        ObjectInputStream ois =
             new ObjectInputStream(new FileInputStream("c:\\jav\\f.txt"));

        System.out.println("Object contains >> " + ois.readObject());

        System.out.println("Transient variable written separately yields >> i ="
                           + ois.readInt());
    }

    public S(int i) {
        this.i = i;
    }

    @Override
    public String toString() {
        return "i= " + i;
    }

}

上面的代码抛出
 Exception in thread "main" java.io.OptionalDataException
    at java.io.ObjectInputStream.readObject0(Unknown Source)
    at java.io.ObjectInputStream.readObject(Unknown Source)
    at com.n.S.main(S.java:27)

但是当我交换输出线像
 System.out.println("Transient variable written separately yields >> i =" + ois.readInt());
 System.out.println("Object contains >> " + ois.readObject());

运行正常。但是为什么会这样呢?我是否必须先编写和读取序列化的基元值,然后再读取或写入对象?什么是OptionalDataException

最佳答案

您需要以与写入ObjectOutputStream完全相同的顺序从ObjectInputStream读取数据。

关于java - Java中的OptionalDataException,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/8630494/

10-11 10:53