日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > java >内容正文

java

java序列化_Java序列化详解

發布時間:2024/9/19 java 28 豆豆
生活随笔 收集整理的這篇文章主要介紹了 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序列化详解的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。