-1

我已经序列化了几个对象Datajava.lang.Integer 但是在使用流Data对象读取数据对象时,未正确读取对象值,而在对象的情况下java.lang.Integer读取的值是正确的。

数据.java

public class Data implements Serializable{
    private Integer count ;
    public void setCount(Integer count ) {
        this.count = count;
        }
    public Integer getCount() {
        return count;
    }
}

序列化测试.java

public class SerializationTest {
    public static void main(String[] args) {
        ObjectOutputStream oos = null;
        ObjectOutputStream oosD = null;
        ObjectInputStream ois = null;
        ObjectInputStream oisD = null;
        try{
            oos = new ObjectOutputStream(new FileOutputStream(new File("integer1.dat"),false));
            oosD = new ObjectOutputStream(new FileOutputStream(new File("Data1.dat"),false));
            Data data = new Data();
            data.setCount(10);
            oos.writeObject(new Integer(10));
            oosD.writeObject(data);

            data.setCount(100);
            oos.writeObject(new Integer(100));
            oosD.writeObject(data);

            data.setCount(1000);
            oos.writeObject(new Integer(1000));
            oosD.writeObject(data);
            oos.close();
            oosD.close();

            ois = new ObjectInputStream(new FileInputStream(new File("integer1.dat")));
            System.out.println("Integer output");
            System.out.println("First Object : "+ (Integer)ois.readObject());           
            System.out.println("Second Object : "+ (Integer)ois.readObject());  
            System.out.println("Third Object : "+ (Integer)ois.readObject());
            ois.close();
            System.out.println("Data output");
            oisD = new ObjectInputStream(new FileInputStream(new File("Data1.dat")));
            System.out.println("First Object : "+ ((Data)oisD.readObject()).getCount());            
            System.out.println("Second Object : "+ ((Data)oisD.readObject()).getCount());   
            System.out.println("Third Object : "+ ((Data)oisD.readObject()).getCount());
            oisD.close();
        }
        catch(IOException ioe){ ioe.printStackTrace();  }
        catch(Exception e){ e.printStackTrace();    }
    }
}

输出 :

Integer output
First Object : 10
Second Object : 100
Third Object : 1000
Data output
First Object : 10
Second Object : 10
Third Object : 10

任何人都可以帮我找出Data对象的问题吗?

4

2 回答 2

4

您每次都在序列化相同的 Data 实例。java 序列化存储对对象的引用,并在您尝试多次存储同一个实例时仅引用先前的存储(这解决了循环引用问题)。每次创建一个新的 Data 实例。

于 2013-05-01T14:36:38.840 回答
0

尝试这个:

        Data data = null;
        data = new Data();
        data.setCount(10);
        oos.writeObject(new Integer(10));
        oosD.writeObject(data);

        data = new Data();
        data.setCount(100);
        oos.writeObject(new Integer(100));
        oosD.writeObject(data);

        data = new Data();
        data.setCount(1000);
        oos.writeObject(new Integer(1000));
        oosD.writeObject(data);
        oos.close();
        oosD.close();
于 2013-05-01T14:42:13.140 回答