搜索
首页Javajava教程Java 中的序列化和反序列化

Serialization and Deserialization In Java

在高级Java中,序列化和反序列化是保存和恢复对象状态的过程,使得可以将对象存储在文件或数据库中,或通过网络传输它们。以下是这些概念及其应用的详细介绍

1️⃣连载

序列化是将对象转换为字节流的过程。该字节流可以保存到文件中、通过网络发送或存储在数据库中。在Java中,Serialized接口用于表示类可以被序列化。

✍ 序列化对象的步骤:

▶️ 实现 Serialized 接口。

▶️ 使用 ObjectOutputStream 和 FileOutputStream 将对象写入文件或输出流。

▶️ 在 ObjectOutputStream 上调用 writeObject() 方法。

?代码示例:

import java.io.FileOutputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;

class Employee implements Serializable {
    private static final long serialVersionUID = 1L;
    String name;
    int id;

    public Employee(String name, int id) {
        this.name = name;
        this.id = id;
    }
}

public class SerializeDemo {
    public static void main(String[] args) {
        Employee emp = new Employee("John Doe", 101);

        try (FileOutputStream fileOut = new FileOutputStream("employee.ser");
             ObjectOutputStream out = new ObjectOutputStream(fileOut)) {
            out.writeObject(emp);
            System.out.println("Serialized data is saved in employee.ser");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

这里,employee.ser 是一个存储对象字节流的序列化文件。

2️⃣ 反序列化
反序列化是相反的过程,其中字节流被转换回原始对象的副本。这使您能够在存储或传输对象后重新创建对象的状态。

✍ 反序列化对象的步骤:

▶️ 使用 ObjectInputStream 和 FileInputStream 从文件或输入流中读取对象。

▶️ 调用 ObjectInputStrea 上的 readObject() 方法

?代码示例:

import java.io.FileInputStream;
import java.io.ObjectInputStream;

public class DeserializeDemo {
    public static void main(String[] args) {
        Employee emp = null;

        try (FileInputStream fileIn = new FileInputStream("employee.ser");
             ObjectInputStream in = new ObjectInputStream(fileIn)) {
            emp = (Employee) in.readObject();
            System.out.println("Deserialized Employee...");
            System.out.println("Name: " + emp.name);
            System.out.println("ID: " + emp.id);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

这将检索对象的原始状态,允许访问其字段,就像序列化之前一样。

3️⃣ 高级连载主题

▶️ 自定义序列化:重写 writeObject() 和 readObject() 以进行自定义序列化。

▶️ 可外部化接口:提供对序列化的完全控制,需要实现 writeExternal() 和 readExternal() 方法。

▶️ 瞬态字段:使用瞬态关键字来避免序列化特定字段(例如密码等敏感数据)。

✍ 序列化的优点:

▶️ 允许保存对象的状态以供将来使用。

▶️ 促进复杂数据对象通过网络的传输。

?简单解释一下代码示例

import java.io.*;

class Student implements Serializable {
    private  static   final long serialVersionUId = 1l;
    private String name ;
    private int  age;
    private String Address;

    public Student(String name,int age,String Address){
        this.name = name;
        this.age = age;
        this.Address = Address;
    }
    public void setName(String name){
        this.name = name;
    }
    public void setAge(int age){
        this.age = age;
    }
    public void setAddress(String Address){
        this.Address = Address;
    }

    public String getName(){
        return name;
    }
    public String getAddress(){
        return Address;
    }
    public int getAge(){
        return age;
    }


    public String toString(){
        return ("Student name is "+this.getName()+", age is "+this.getAge()+", and address is "+this.getAddress());
    }
}

public class  JAVA3_Serialization {
    // when you implement Serializable then you must be write a serialVersionUId because when it serialise and deserialize it uniquely identify in the network
    // when u update ur object or anything then you have to update the serialVersionUId increment .
    // private  static   final long serialVersionUId = 1l;

    // transient  int x ;
    // If you do not want a particular value to serialise and Deserialize.
    // the value x, when you don't serialise and Deserialize Then transient you used.

    public static void main(String[] args) {

        Student student = new Student("kanha",21,"angul odisha");

        String filename = "D:\Advance JAVA\CLS3 JAVA\Test.txt"; // store the data in this location
        FileOutputStream fileOut = null; // write file
        ObjectOutputStream objOut = null; // create object
        //Serialization
        try {
            fileOut = new FileOutputStream(filename);
            objOut = new ObjectOutputStream(fileOut);
            objOut.writeObject(student);

            objOut.close();
            fileOut.close();

            System.out.println("Object has been serialise =\n"+student);
        } catch (IOException ex){
            System.out.println("error will occure");
        }

        //Deserialization
        FileInputStream fileIn = null;
        ObjectInputStream objIn = null;
        try {
            fileIn = new FileInputStream(filename);
            objIn = new ObjectInputStream(fileIn);
            Student object =(Student) objIn.readObject();
            System.out.println("object has been Deserialization =\n"+object);

            objIn.close();
            fileIn.close();

        } catch (IOException e) {
            throw new RuntimeException(e);
        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        }
    }
}

✍ 要点:

▶️ 默认情况下仅序列化非静态和非瞬态数据成员。

▶️ 如果序列化后修改了类,可序列化对象必须确保版本之间的兼容性。

如需更多见解,请随时提及您的 GitHub 以获取深入的示例和代码示例!如果您需要任何具体调整,请告诉我。

GitHub - https://github.com/Prabhanjan-17p

以上是Java 中的序列化和反序列化的详细内容。更多信息请关注PHP中文网其他相关文章!

声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn

热AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover

AI Clothes Remover

用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool

Undress AI Tool

免费脱衣服图片

Clothoff.io

Clothoff.io

AI脱衣机

AI Hentai Generator

AI Hentai Generator

免费生成ai无尽的。

热工具

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

功能强大的PHP集成开发环境

记事本++7.3.1

记事本++7.3.1

好用且免费的代码编辑器

mPDF

mPDF

mPDF是一个PHP库,可以从UTF-8编码的HTML生成PDF文件。原作者Ian Back编写mPDF以从他的网站上“即时”输出PDF文件,并处理不同的语言。与原始脚本如HTML2FPDF相比,它的速度较慢,并且在使用Unicode字体时生成的文件较大,但支持CSS样式等,并进行了大量增强。支持几乎所有语言,包括RTL(阿拉伯语和希伯来语)和CJK(中日韩)。支持嵌套的块级元素(如P、DIV),

EditPlus 中文破解版

EditPlus 中文破解版

体积小,语法高亮,不支持代码提示功能

Dreamweaver CS6

Dreamweaver CS6

视觉化网页开发工具