我已经序列化了几个Data
和java.lang.Integer
个对象,但是在使用流Data
读取数据对象时,如果java.lang.Integer
对象读取的值为对象,则无法正确读取对象值正确的。
Data.java
public class Data implements Serializable{
private Integer count ;
public void setCount(Integer count ) {
this.count = count;
}
public Integer getCount() {
return count;
}
}
SerializationTest.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
对象的问题吗?
答案 0 :(得分:4)
您每次都在序列化相同的数据实例。 java序列化存储对象的引用,并在您尝试多次存储同一实例时引用先前的存储(这解决了循环引用问题)。每次都创建一个新的数据实例。
答案 1 :(得分: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();