序列化是将对象转换为字节流的过程,反序列化是从该字节流重建对象的过程。在 Java 中使用数组时,有效地序列化和反序列化它们对于数据存储和传输至关重要。
下面是Java中数组序列化和反序列化的实现:
// Java Program to Serialize // And Deserialize Arrays import java.io.*;
// Driver Class public class GFG { // Main Function public static void main(String[] args) { int[] intArray = {10, 20, 30, 40, 50}; // Serialization try (ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("array.ser"))) { out.writeObject(intArray); } catch (IOException e) { e.printStackTrace(); } // 反序列化 ; try (ObjectInputStream in = new ObjectInputStream(new FileInputStream("array.ser"))) { int[] deserializedArray = (int[]) in.readObject(); for (int num : deserializedArray) { System.out.print(num + " "); } } catch (IOException | ClassNotFoundException e) { e.printStackTrace(); } } }
|
输出 :
10 20 30 40 50
该程序分为序列化和反序列化两部分。
1、序列化:
ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("array.ser"))
这里创建的字节流存储在out变量中,并用“array.ser”初始化为写入数组的文件。
下一步是,out.writeObject(intArray);
这里“array.ser”填充了intArray的内容。
2、反序列化:
ObjectInputStream in = new ObjectInputStream(new FileInputStream("array.ser"))
这里的in用于读取“array.ser”。
之后:
int[] deserializedArray = (int[]) in.readObject();
它只是从文件中提取数据,然后填充数组元素。