|
√ Google adsense申请技巧 √ 本站核心代理域名注册主机业务
√ 快速发布你的买卖域名买卖网站信息
√ 1元注册 cn域名
√ 站长每日新闻导读 √ ·推荐万网空间¥120元 150m √ 站长网:站长必上的网站 √ 网站联盟大全 √ 本站代理万网域名55空间120元 |
以下的代码定义了一个简单的BugReport对象,它实现了最简单的序列化接口。
1 import java.Io.*;
2 public class BugReport implements Serializable {
3 private Float m_SoftwareVersion; // version number from Help.About, e.g. "1.0"
4 private String m_ErrorDescription; // Description of error
5 private int m_Severity; // 1=System unusable - 5=Minor Aesthetic defect
6 public BugReport (Float SoftwareVersion, String ErrorDescription, int Severity) {
7 m_SoftwareVersion = SoftwareVersion;
8 m_ErrorDesctiption = ErrorDescription;
9 m_Severity = Severity;
10 }
11 public BugReport () {} // for reconstituting serialized objects
12 public void save (OutputStream os)
13 throws IOException {
14 try {
15 ObjectOutputStream o = new ObjectOutputStream(os);
16 o.writeObject(this);
17 o.flush();
18 }
19 catch (IOException e) {throw e;}
20 }
21 public BugReport restore (InputStream is)
22 throws IOException, ClassNotFoundException {
23 BugReport RestoredBugReport = null;
24 try {
25 ObjectInputStream o = new ObjectInputStream(is);
26 RestoredBugReport = (BugReport)o.readObject();
27 }
28 catch (IOException e) {throw e;}
29 catch (ClassNotFoundException e) {throw e;}
30 return RestoredBugReport;
31 }
32 }
1使用import语句引入I/O包,包括序列化接口。
2-5定义类中的成员变量,并指出该类实现了序列化接口。
6-10提供一个简单的构造函数
11一个空的构造函数。这个构造函数在重建序列化对象时使用。见以下的例子。
12-20定义一个方法函数,它把对象写入一个已经打开了的ObjectOutputStream。这个方 法函数首先创建一个ObjectOutputStream对象,然后调用writeObject方法函数,最后在 函数返回前显式清空输出缓冲区。
21-30定义一个方法函数,它从一个打开了的InputStream中读入一个BugReport对象。注 意,如果输入流中下一个对象和正在读入对象的类型不一致时,readObject()将会抛出一 个异常。
使用BugReport对象相当简单。譬如我们想要创建一个新的BugReport对象并且把它存入 一个文件,我们会用到以下代码:
1 import java.io.*;
.
.
2 BugReport bug = new BugReport(1.0, "Crashes when spell checker invoked", 2);
3 FileOUtputStream os = new FileOutputStream("MyBug.test");
4 bug.save(os);
很简单,对吗?当然,一旦对象已经被序列化,没有人能阻止你继续操纵对象的状态。上一 个例子中包涵了一个在被写入磁盘时已经存在对象的拷贝。因此你必须要十分谨慎,以防 在对对象做出所有的修改之后没有序列化对象,从而丢失了对象的状态修改信息。