对J2SE中的序列化的一个感性的认识
来源:互联网 发布:网络竞速游戏排行榜 编辑:程序博客网 时间:2024/05/16 19:03
ava中处处体现着简单的程序设计风格,序列化作为最常用的功能之一,在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
正确打印了结果。
- 对J2SE中的序列化的一个感性的认识
- 谈谈J2SE中的序列化之一个感性的认识
- 谈谈J2SE中的序列化之一个感性的认识
- J2SE中的序列化的认识
- 对序列化的认识
- 第四十讲 感性的认识线程
- J2SE的初认识
- Go语言基础学习一:对go的感性初步认识
- 一个直观感性的方法认识linux的系统驱动架构
- java中的类是动态加载的,我们先看一下我们常用的类加载方式,先有一个感性的认识,才能进一步
- 序列化的认识
- 谈谈J2SE中的序列化
- 谈谈J2SE中的序列化
- 谈谈J2SE中的序列化
- 谈谈J2SE中的序列化
- 对数据库的一个认识
- 20161018对linux软件安装和使用的感性
- 纯人文化的内存感性回忆录
- WinCE动态修改启动LOGO
- android中setTheme 放置位置要注意
- 开始被管了。
- HOOK的初步学习(非全局钩子)!
- 各种hash函数
- 对J2SE中的序列化的一个感性的认识
- 设置Android程序全屏
- C++中的虚函数与函数重载
- VC下的DLL学习心得!
- 基于MongoDB的php应用开发
- perl module
- Android ListView Adapter
- J2SE5.0新特性之使用代理服务器
- 全局HOOK的实现学习!