本帖最后由 吴文华 于 2012-2-18 14:00 编辑
其实很简单,一个对象对于我们来说的意义其实就是对象里保存的那些数据,序列化就是把这些数据转换成二进制 表示的对象流,你可以把它通过网络传输到远程,当然,也可以把这些信息保存在本地的文件里。下面给出一个最简单的Java的序列化与反序列化的例子,看懂 这个例子,相信你应该能大概理解这是怎么一回事了。
首先是一个Peraon类:
Person.java
Java代码
package com.lanber.serial;
import java.io.Serializable;
public class Person implements Serializable {
private String name;
private int age;
private String sex;
private String nationality;
public Person(String _name, int _age, String _sex, String _nationality) {
this.name = _name;
this.age = _age;
this.sex = _sex;
this.nationality = _nationality;
}
public String toString() {
return "Name:" + name + "\nAge:" + age + "\nSex:" + sex
+ "\nNationality:" + nationality + "\n\n";
}
}
package com.lanber.serial; import java.io.Serializable; public class Person implements Serializable { private String name; private int age; private String sex; private String nationality; public Person(String _name, int _age, String _sex, String _nationality) { this.name = _name; this.age = _age; this.sex = _sex; this.nationality = _nationality; } public String toString() { return "Name:" + name + "\nAge:" + age + "\nSex:" + sex + "\nNationality:" + nationality + "\n\n"; } }
而后我们要实例化一个Person对象,把我们实例化出来的这个对象序列化,并把序列化后的对象流保存到文件中去:
WritePerson.java
Java代码
package com.lanber.serial;
import java.io.*;
public class WritePerson {
public static void main(String[] args) {
try {
ObjectOutputStream oos = new ObjectOutputStream(
new FileOutputStream("Person.tmp"));
Person obj = new Person("Tony", 25, "Female", "han");
System.out.println("将Person对象写入到文件Person.tmp中...");
oos.writeObject(obj);
oos.close();
System.out.println("完成!");
} catch (Exception e) {
System.out.println(e);
}
}
}
package com.lanber.serial; import java.io.*; public class WritePerson { public static void main(String[] args) { try { ObjectOutputStream oos = new ObjectOutputStream( new FileOutputStream("Person.tmp")); Person obj = new Person("Tony", 25, "Female", "han"); System.out.println("将Person对象写入到文件Person.tmp中..."); oos.writeObject(obj); oos.close(); System.out.println("完成!"); } catch (Exception e) { System.out.println(e); } } }
这样,我们就把序列化后的二进制对象流保存到Person.tmp的文件中去了(特别要注意这里的oos.writeObject()方法, 这个方法就是实现把obj对象序列化的方法)。你可以打开生成的这个文件查看,不过我们是看不懂这里面的信息的,因为这是二进制数据啊。 |