21xrx.com
2024-09-20 05:55:42 Friday
登录
文章检索 我的文章 写文章
Java中的序列化与反序列化
2023-06-16 12:04:56 深夜i     --     --
Java 序列化 反序列化

在Java中,对象序列化是将对象转换为字节流的过程,以便将其保存到文件中或通过网络传输到另一个计算机。Java中的反序列化是将字节数组转换回对象的过程。这是一种有用的技术,因为它允许我们在不同的计算机之间传输对象,而无需重新创建它们。在本文中,我们将探讨Java中的序列化与反序列化,并通过实际的代码案例来演示其用法。

Java中的序列化常常会用到java.io.Serializable接口,先看下面这个例子:


import java.io.*;

public class SerializationDemo {

  public static void main(String [] args) {

   Employee e = new Employee();

   e.name = "Mike";

   e.address = "123 Main St";

   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();

   }

  }

}

在这个例子中,我们创建了一个Employee对象,并将其写入到磁盘上的一个名为employee.ser的文件中。该文件的位置为/tmp/employee.ser。

接下来,我们将演示如何从文件中读取对象并反序列化它。请看下面的代码示例:


import java.io.*;

public class DeserializationDemo {

  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);

  }

}

在这个例子中,我们使用ObjectInputStream从磁盘读取位于/tmp/employee.ser位置的文件,并使用Employee类中的name,address,SSN和number属性反序列化该对象。

以上就是Java中的序列化和反序列化的用法和实例演示。我们可以看到,通过序列化和反序列化技术,我们可以轻松地传输和存储Java对象。这为我们提供了更方便的方式来传输和处理数据。

  
  

评论区

{{item['qq_nickname']}}
()
回复
回复