gpt4 book ai didi

java - 初始化 int 数组中的值后,对该数组的更新将不会出现在 Serial 中

转载 作者:行者123 更新时间:2023-12-02 02:49:43 25 4
gpt4 key购买 nike

我一直在研究序列化对象,以便我可以轻松快速地通过网络发送对象。但这有一个大问题。在初始化数组中的值后,该数组的序列化对象将始终保持为初始化的数字。我什至不确定是否是这种情况,因为我很确定整数的默认值为 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

我该如何解决这个问题?

更新:

经过进一步的实验,我发现对象被序列化一次后,它的序列号似乎没有改变。如此处所示,我编辑了字符串数组,它的内容在通过对象流发送后没有改变

    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

最佳答案

在更改输出流之前重置它。

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();
}

关于java - 初始化 int 数组中的值后,对该数组的更新将不会出现在 Serial 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44037540/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com