在Java中,序列化和反序列化是將對象轉換為字節流以便在網絡中傳輸或存儲,然后再將字節流還原為對象的過程。Java提供了java.io.Serializable接口來支持對象的序列化。
以下是一個簡單的示例,展示了如何創建一個可序列化的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 +
'}';
}
}
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();
}
}
}
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對象,并打印其屬性。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。