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

   2024-10-02 2280
核心提示:在Java中,可以使用ObjectOutputStream和ObjectInputStream来实现数组的序列化和反序列化。数组的序列化:int[] array = {1, 2,

在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。

 
举报打赏
 
更多>同类物流大全
推荐图文
推荐物流大全
点击排行

网站首页  |  关于我们  |  联系方式 | 网站留言    |  赣ICP备2021007278号