Java 中序列化和反序列化之間的區別是什麼?


序列化

 Java 提供了一種機制,稱為物件序列化,其中物件可以表示為一個位元組序列,包括物件的資料以及有關物件型別和儲存在物件中資料型別的資訊。

示例

import java.io.*;

public class SerializeDemo {
   public static void main(String [] args) {
      Employee e = new Employee();
      e.name = "Reyan Ali";
      e.address = "Phokka Kuan, Ambehta Peer";
      e.SSN = 11122333;
      e.number = 101;

      try {
         FileOutputStream fileOut = new FileOutputStream("/tmp/employee.ser");
         ObjectOutputStream out = new ObjectOutputStream(fileOut);
         out.writeObject(e);
         out.close();
         fileOut.close();
         System.out.printf("Serialized data is saved in /tmp/employee.ser");
      } catch (IOException i) {
         i.printStackTrace();
      }
   }
}

反序列化

 將序列化物件寫入檔案後,可以從檔案中讀取該物件並對其進行反序列化,即,表示物件及其資料的資訊和位元組可用於在記憶體中重新建立物件。

示例

import java.io.*;

public class DeserializeDemo {
   public static void main(String [] args) {
      Employee e = null;
     
      try {
         FileInputStream fileIn = new FileInputStream("/tmp/employee.ser");
         ObjectInputStream in = new ObjectInputStream(fileIn);
         e = (Employee) in.readObject();
         in.close();
         fileIn.close();
      } catch (IOException i) {
         i.printStackTrace();
         return;
      } catch (ClassNotFoundException c) {
         System.out.println("Employee class not found");
         c.printStackTrace();
         return;
      }
      System.out.println("Deserialized Employee...");
      System.out.println("Name: " + e.name);
      System.out.println("Address: " + e.address);
      System.out.println("SSN: " + e.SSN);
      System.out.println("Number: " + e.number);
   }
}

輸出

Deserialized Employee...
Name: Reyan Ali
Address:Phokka Kuan, Ambehta Peer
SSN: 0
Number:101

更新於: 2020 年 2 月 25 日

2K+ 瀏覽量

開始你的 職業生涯

完成課程並獲得認證

開始
廣告
© . All rights reserved.