java序列化_Java序列化详解

ac057f4b3ca7215f0813842786713f11.png

什么是序列化?

在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的资料与面试题,如果你在技术上面想提升自己的话,可以关注我,私信发送领取资料或者在评论区留下自己的联系方式,有时间记得帮我点下转发让跟多的人看到哦。

e17b73c806cab0e5342fb788623fdc32.png

d20815f8653808ccd68d4d068b0b82fc.png
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值