J2SE中的序列化的认识
技术  /  管理员 发布于 7年前   263
java中处处体现着简单的程序设计风格,序列化作为最常用的功能之一,在java中的设计尤为“简单”。在ObjectInputStream 和ObjectOutputStream的帮助下,我们可以轻松的实现序列化。
只要我们的class 实现了java.io.Serializable接口,就可以利用ObjectOutputStream的writeObject()方法将一个对象序列化;利用ObjectInputStream的readObject()方法,可以返回读出的object对象。Serializable接口不需要我们实现任何方法。
以下是一个例子,它能给我们一个感性的认识:
Serial实现了就java.io.Serializable接口,是需要序列化的类。我们首先构造一个Serial的对象serial1然后将其保存(序列化)在一个文件中,而后再将其读出(反序列化),并打印其内容。
package Stream;
/**
* @author favo yang
*/
import java.io.*;
public class Serial implements Serializable {
int company_id;
String company_addr;
boolean company_flag;
public Serial(){}//不同于c++,没有也可以
public Serial(int company_id,String company_addr,boolean company_flag) {
this.company_id=company_id;
this.company_addr=company_addr;
this.company_flag=company_flag;
}
public static void main(String[] args) {
Serial serial1 = new Serial(752,"dayer street #5 building 02-287",false);//构造一个新的对象
FileInputStream in=null;
FileOutputStream out=null;
ObjectInputStream oin=null;
ObjectOutputStream oout=null;
try {
out = new FileOutputStream("5.txt");
oout = new ObjectOutputStream(out);
serial1.serialize(oout);//序列化
oout.close();
oout=null;
in = new FileInputStream("5.txt");
oin = new ObjectInputStream(in);
Serial serial2 = Serial.deserialize(oin);//反序列化
System.out.println(serial2);//打印结果
} catch (Exception ex){
ex.printStackTrace();
} finally{
try {
if (in != null) {
in.close();
}
if (oin != null) {
oin.close();
}
if (out != null) {
out.close();
}
if (oout != null) {
oout.close();
}
} catch (IOException ex1) {
ex1.printStackTrace();
}
}
}
/**
* deserialize
*/
public static Serial deserialize(ObjectInputStream oin) throws Exception{
Serial s=(Serial)oin.readObject();
return s;
}
public String toString() {
return "DATA: "+company_id+" "+company_addr+" "+company_flag;
}
/**
* serialize
*/
public void serialize(ObjectOutputStream oout) throws Exception{
oout.writeObject(this);
}
}
运行结果:
DATA: 752 dayer street #5 building 02-287 false
正确打印了结果。
122 在
学历:一种延缓就业设计,生活需求下的权衡之选中评论 工作几年后,报名考研了,到现在还没认真学习备考,迷茫中。作为一名北漂互联网打工人..123 在
Clash for Windows作者删库跑路了,github已404中评论 按理说只要你在国内,所有的流量进出都在监控范围内,不管你怎么隐藏也没用,想搞你分..原梓番博客 在
在Laravel框架中使用模型Model分表最简单的方法中评论 好久好久都没看友情链接申请了,今天刚看,已经添加。..博主 在
佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 @1111老铁这个不行了,可以看看近期评论的其他文章..1111 在
佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 网站不能打开,博主百忙中能否发个APP下载链接,佛跳墙或极光..
Copyright·© 2019 侯体宗版权所有·
粤ICP备20027696号