溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

Java Public類的序列化與反序列化

發布時間:2025-01-23 14:06:39 來源:億速云 閱讀:109 作者:小樊 欄目:編程語言

在Java中,序列化和反序列化是將對象轉換為字節流以便在網絡中傳輸或存儲,然后再將字節流還原為對象的過程。Java提供了java.io.Serializable接口來支持對象的序列化。

以下是一個簡單的示例,展示了如何創建一個可序列化的Public類,以及如何進行序列化和反序列化操作:

  1. 創建一個可序列化的Public類:
import java.io.Serializable;

public class Person implements Serializable {
    private String name;
    private int age;

    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    @Override
    public String toString() {
        return "Person{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}
  1. 序列化對象:
import java.io.*;

public class SerializeDeserializeExample {
    public static void main(String[] args) {
        Person person = new Person("John Doe", 30);

        try {
            // 序列化對象
            FileOutputStream fileOut = new FileOutputStream("person.ser");
            ObjectOutputStream out = new ObjectOutputStream(fileOut);
            out.writeObject(person);
            out.close();
            fileOut.close();
            System.out.printf("Serialized data is saved in person.ser");
        } catch (IOException i) {
            i.printStackTrace();
        }
    }
}
  1. 反序列化對象:
import java.io.*;

public class SerializeDeserializeExample {
    public static void main(String[] args) {
        Person person = null;
        try {
            // 反序列化對象
            FileInputStream fileIn = new FileInputStream("person.ser");
            ObjectInputStream in = new ObjectInputStream(fileIn);
            person = (Person) in.readObject();
            in.close();
            fileIn.close();
        } catch (IOException i) {
            i.printStackTrace();
            return;
        } catch (ClassNotFoundException c) {
            System.out.println("Person class not found");
            c.printStackTrace();
            return;
        }

        System.out.println("Deserialized Person...");
        System.out.println("Name: " + person.getName());
        System.out.println("Age: " + person.getAge());
    }
}

在這個示例中,我們創建了一個名為Person的Public類,并實現了Serializable接口。然后,我們創建了一個Person對象,并將其序列化到名為person.ser的文件中。接下來,我們從該文件中反序列化Person對象,并打印其屬性。

向AI問一下細節

免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。

AI

亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女