**
* 对象序列化与反序列化
*
* @author 聂鑫
* @email
[email protected]
*
*/
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
/* 需要持久化的类
* 要想使类支持对象序列化,只需要实现Serializable接口
*/
class Person implements Serializable {
/* 属性 */
private String id;
private String password;
private String name;
private int age;
// 如果不想对某些属性进行序列化,则需加上transient修饰符
private transient String sex;
/* setter和getter方法 */
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
/* 覆盖toString方法 */
public String toString() {
return "对象信息:" + id + " " + password + " " + name + " " + age + " " + sex;
}
}
/*
* 实现了对象序列化和反序列化的类
*/
public class SeriObject {
/**
* 序列化
*
* @param person 对象名
* @param file 指定文件
*/
public void writePerson(Person person, String file) {
try {
// 对象输出流,指向指定文件
ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(file));
out.writeObject(person);// 将对象写入文件
out.flush();// 清空
out.close();// 关闭
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 反序列化
*
* @param file 指定文件
*/
public void readPerson(String file) {
try {
// 对象输入流,来源于指定文件
ObjectInputStream in = new ObjectInputStream(new FileInputStream(file));
Object o = in.readObject();// 将对象从文件读出
in.close();// 关闭
if (o != null) {
if (o instanceof Person)
System.out.println(o.toString());
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
/*
* 测试代码
*/
Person person = new Person();
person.setId("aaa");
person.setPassword("bbb");
person.setName("张三");
person.setAge(20);
person.setSex("男");
SeriObject so = new SeriObject();
so.writePerson(person, "person.txt");
so.readPerson("person.txt");
}
}