java序列化_Java序列化详解
什么是序列化?
在Java中,對象序列化表示將對象表示為字節序列。字節包括對象的數據和信息。可以將序列化的對象寫入文件/數據庫,然后從文件/數據庫中讀取并反序列化。代表對象及其數據的字節可用于在內存中重新創建對象。
為什么我們需要序列化?
當您需要通過網絡發送對象或存儲在文件中時,通常使用序列化。網絡基礎結構和硬盤只能理解位和字節,而不能理解Java對象。序列化將Java對象轉換為字節,然后通過網絡發送或保存。
為什么我們要存儲或傳輸對象?在我的編程經驗中,有以下原因促使我使用可序列化的對象。
1. 對象的創建取決于很多上下文。創建后,其他組件需要其方法及其字段。
2. 創建對象并包含許多字段時,我們不確定該使用什么。因此,將其存儲到數據庫以供以后進行數據分析。
Java序列化示例
下面的示例演示如何使一個類可序列化以及對其進行序列化和反序列化。
package serialization;
import java.io.Serializable;
public class Dog implements Serializable {
private static final long serialVersionUID = -5742822984616863149L;
private String name;
private String color;
private transient int weight;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
public int getWeight() {
return weight;
}
public void setWeight(int weight) {
this.weight = weight;
}
public void introduce() {
System.out.println("I have a " + color + " " + name + ".");
}}
package serialization;
import java.io.FileInputStream;import java.io.FileOutputStream;import java.io.IOException;import java.io.ObjectInputStream;import java.io.ObjectOutputStream;
public class SerializeDemo {
public static void main(String[] args) {
//create an object
Dog e = new Dog();
e.setName("bulldog");
e.setColor("white");
e.setWeight(5);
//serialize
try {
FileOutputStream fileOut = new FileOutputStream("./dog.ser");
ObjectOutputStream out = new ObjectOutputStream(fileOut);
out.writeObject(e);
out.close();
fileOut.close();
System.out.printf("Serialized dog is saved in ./dog.ser");
} catch (IOException i) {
i.printStackTrace();
}
e = null;
//Deserialize
try {
FileInputStream fileIn = new FileInputStream("./dog.ser");
ObjectInputStream in = new ObjectInputStream(fileIn);
e = (Dog) in.readObject();
in.close();
fileIn.close();
} catch (IOException i) {
i.printStackTrace();
return;
} catch (ClassNotFoundException c) {
System.out.println("Dog class not found");
c.printStackTrace();
return;
}
System.out.println("nDeserialized Dog ...");
System.out.println("Name: " + e.getName());
System.out.println("Color: " + e.getColor());
System.out.println("Weight: " + e.getWeight());
e.introduce();
}}
Output:
Serialized dog is saved in ./dog.ser
Deserialized Dog...
Name: bulldog
Color: white
Weight: 0
I have a white bulldog.
最后,開發這么多年我也總結了一套學習Java的資料與面試題,如果你在技術上面想提升自己的話,可以關注我,私信發送領取資料或者在評論區留下自己的聯系方式,有時間記得幫我點下轉發讓跟多的人看到哦。
總結
以上是生活随笔為你收集整理的java序列化_Java序列化详解的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: android新浪微博sdk登录获取用户
- 下一篇: 撞鬼了代表什么意思,脸变成青色眼镜周围都