在Java中,可以使用ObjectOutputStream和ObjectInputStream來實現數組的序列化和反序列化。
int[] array = {1, 2, 3, 4, 5};
try {
FileOutputStream fileOut = new FileOutputStream("array.ser");
ObjectOutputStream out = new ObjectOutputStream(fileOut);
out.writeObject(array);
out.close();
fileOut.close();
System.out.println("Array serialized successfully");
} catch (IOException e) {
e.printStackTrace();
}
int[] array = null;
try {
FileInputStream fileIn = new FileInputStream("array.ser");
ObjectInputStream in = new ObjectInputStream(fileIn);
array = (int[]) in.readObject();
in.close();
fileIn.close();
System.out.println("Array deserialized successfully");
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
}
// 打印反序列化后的數組元素
for (int i : array) {
System.out.println(i);
}
需要注意的是,序列化和反序列化時,數組元素的類型必須是可序列化的類型,否則會拋出NotSerializableException。