温馨提示×

Java中Array的序列化与反序列化

小樊
93
2024-08-06 07:44:09
栏目: 编程语言
Java开发者专用服务器限时活动,0元免费领,库存有限,领完即止! 点击查看>>

在Java中,可以使用ObjectOutputStream和ObjectInputStream来实现数组的序列化和反序列化。

  1. 数组的序列化:
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();
}
  1. 数组的反序列化:
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。

亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>

推荐阅读:Java序列化与反序列化如何实现

0