21xrx.com
2024-09-20 05:34:04 Friday
登录
文章检索 我的文章 写文章
"深入了解JAVA中serialize的作用"
2023-06-16 21:53:18 深夜i     --     --
Java 序列化

Java 中的序列化是指将对象转化为字节流,以便在网络中传输或保存到本地,Serializable 接口负责标识出可序列化的类。在实际应用中,Java 的序列化机制被广泛用于实现远程传输、对象持久化等功能。

下面是一个简单的实例,展示如何使用 Java 的序列化机制将对象序列化到文件中,并从该文件中反序列化对象:


import java.io.*;

public class SerialDemo {

  public static void main(String[] args) {

    String fileName = "/tmp/helloWorld.dat";

    // 序列化对象

    try {

      FileOutputStream fileOut = new FileOutputStream(fileName);

      ObjectOutputStream out = new ObjectOutputStream(fileOut);

      out.writeObject("Hello, World!");

      out.close();

      fileOut.close();

      System.out.printf("Serialized data is saved in %s\n", fileName);

    } catch (IOException i) {

      i.printStackTrace();

    }

    // 反序列化对象

    try {

      FileInputStream fileIn = new FileInputStream(fileName);

      ObjectInputStream in = new ObjectInputStream(fileIn);

      String helloWorld = (String) in.readObject();

      System.out.printf("The deserialized data is: %s\n", helloWorld);

      in.close();

      fileIn.close();

    } catch (IOException i) {

      i.printStackTrace();

    } catch (ClassNotFoundException c) {

      System.out.println("Class not found");

      c.printStackTrace();

    }

  }

}

上述代码通过 FileOutputStream 将字符串 "Hello, World!" 写入到文件 "/tmp/helloWorld.dat" 中,然后再通过 FileInputStream 从该文件中读取字符串并输出到控制台。实现了一个简单的序列化和反序列化操作。

、可序列化的类、远程传输、对象持久化。

  
  

评论区

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