Python 官方文档:入门教程 => 点击学习
序列化 序列化:将对象转换为二进制序列在网络中传输或保存到磁盘 反序列化:从网络或磁盘中将二进制序列转换为对象 注意: 对象必须实现Serializable接口 对象的所有属性都要
序列化:将对象转换为二进制序列在网络中传输或保存到磁盘
反序列化:从网络或磁盘中将二进制序列转换为对象
注意:
对象必须实现Serializable接口
对象的所有属性都要能序列化(Integer,Byte等都进行了序列化)
String
Integer
1.编写大象类
public class Elephant implements Serializable {
private String name;
private String age;
private String sex;
public Elephant(String name, String age, String sex) {
this.name = name;
this.age = age;
this.sex = sex;
}
@Override
public String toString() {
return "Elephant{" +
"name='" + name + '\'' +
", age='" + age + '\'' +
", sex='" + sex + '\'' +
'}';
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAge() {
return age;
}
public void setAge(String age) {
this.age = age;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
}
2.大象测试类
public class ElephantTest {
public static final String PATH = "D:\\elephant";
static void write(Elephant elephant){
//创建对象输出流
try( ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(PATH))) {
//写入对象
out.writeObject(elephant);
} catch (ioException e) {
e.printStackTrace();
}
}
static Object read(){
//创建对象输出流
try( ObjectInputStream in = new ObjectInputStream(new FileInputStream(PATH))) {
//写入对象
return in.readObject();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
public static void main(String[] args) {
Elephant elephant7 = new Elephant("小红象", "18", "男");
write(elephant7);
Elephant elephant1 = (Elephant) read();
System.out.println(elephant1);
System.out.println(elephant7);
System.out.println(elephant1==elephant7);
}
}
运行结果:
写入D盘的对象:
到此这篇关于Java序列化和反序列化的文章就介绍到这了,更多相关Java序列化和反序列化内容请搜索编程网以前的文章或继续浏览下面的相关文章希望大家以后多多支持编程网!
--结束END--
本文标题: 图文浅析Java序列化和反序列化
本文链接: https://www.lsjlt.com/news/126073.html(转载时请注明来源链接)
有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341
下载Word文档到电脑,方便收藏和打印~
2024-03-01
2024-03-01
2024-03-01
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
回答
回答
回答
回答
回答
回答
回答
回答
回答
回答
0