在初始化int数组中的值之后,对数组的更新将不会出现在序列

时间:2017-05-18 02:19:57

标签: java arrays serialization initialization

我一直在研究序列化对象,以便我可以轻松快速地通过网络发送对象。尽管如此,这还有一个重大问题。在我的数组中初始化一个值后,该数组的序列化对象将始终保持为初始化的数字。我甚至不确定是否是这种情况,因为我非常确定它的默认值为0.所以它不会保持为0而不是我改为它吗?

public static void main(String[] args) throws FileNotFoundException, IOException, ClassNotFoundException {
    FileOutputStream ostr = new FileOutputStream(new File("ObjectFile.yeh"));
    FileInputStream istr = new FileInputStream(new File("ObjectFile.yeh"));
    ObjectOutputStream out= new ObjectOutputStream(ostr);
    int[] hi = new int[5];
    hi[0]=3;
    out.writeUTF("This is an Array");
    out.writeObject(hi);
    hi[0]=5;
    out.writeObject(hi);
    out.writeUTF("Array Over");
    out.close();
    ObjectInputStream in = new ObjectInputStream(istr);
    System.out.println(in.readUTF());
    int[] h = (int[]) in.readObject();
    System.out.println(h[0]);
    int[] j = (int[]) in.readObject();
    System.out.println(j[0]);
    System.out.println(in.readUTF());
    in.close();
}

当我运行以下代码时,它会打印

This is an Array
3
3
Array Over

我该如何解决这个问题?

更新

经过进一步的实验,我发现在对象被序列化一次后,它的序列似乎没有改变。如下所示,我编辑了String数组,它的内容在通过Object Stream发送后不会改变

    public static void main(String[] args) throws FileNotFoundException, IOException, ClassNotFoundException {
    FileOutputStream ostr = new FileOutputStream(new File("ObjectFile.yeh"));
    FileInputStream istr = new FileInputStream(new File("ObjectFile.yeh"));
    ObjectOutputStream out= new ObjectOutputStream(ostr);
    String[] hi = new String[5];
    hi[0]="Hi";
    out.writeUTF("This is an Array");
    out.writeObject(hi);
    hi[0]="Hello";
    hi[1]="Hoopla";
    out.writeObject(hi);
    out.writeUTF("Array Over");
    out.close();
    ObjectInputStream in = new ObjectInputStream(istr);
    System.out.println(in.readUTF());
    String[] h = (String[]) in.readObject();
    System.out.println(h[0]+" "+h[1]);
    String[] j = (String[]) in.readObject();
    System.out.println(j[0]+" "+j[1]);
    System.out.println(in.readUTF());
    in.close();
}

这打印

This is an Array
Hi null
Hi null
Array Over

1 个答案:

答案 0 :(得分:2)

在更改之前重置输出流。

public static void main(String[] args) throws FileNotFoundException, IOException, ClassNotFoundException {
    FileOutputStream ostr = new FileOutputStream(new File("ObjectFile.yeh"));
    FileInputStream istr = new FileInputStream(new File("ObjectFile.yeh"));
    ObjectOutputStream out= new ObjectOutputStream(ostr);
    int[] hi = new int[5];
    hi[0]=3;
    out.writeUTF("This is an Array");
    out.writeObject(hi);
    out.reset(); // Add this line
    hi[0]=5;
    out.writeObject(hi);
    out.writeUTF("Array Over");
    out.close();
    ObjectInputStream in = new ObjectInputStream(istr);
    System.out.println(in.readUTF());
    int[] h = (int[]) in.readObject();
    System.out.println(h[0]);
    int[] j = (int[]) in.readObject();
    System.out.println(j[0]);
    System.out.println(in.readUTF());
    in.close();
}