黑马程序员技术交流社区
标题:
java 序列化与反序列化
[打印本页]
作者:
marcojam
时间:
2015-8-9 21:15
标题:
java 序列化与反序列化
package objectinputStream;
import java.io.Serializable;
//Serializable接口没有实现方法,此接口为标签接口,使类具有序列化功能
public class Person implements Serializable{
/**
*
*/
//自动生成序列化uid值,可以读取保存的对象
private static final long serialVersionUID = 1523235872808630995L;
private String name;
//加上transient关键字使该成员变量不能被序列化
private transient int age;
public Person(String name, int age) {
super();
this.name = name;
this.age = age;
}
public Person() {
super();
// TODO 自动生成的构造函数存根
}
/**
* @return name
*/
public String getName() {
return name;
}
/**
* @param name 要设置的 name
*/
public void setName(String name) {
this.name = name;
}
/**
* @return age
*/
public int getAge() {
return age;
}
/**
* @param age 要设置的 age
*/
public void setAge(int age) {
this.age = age;
}
/* (非 Javadoc)
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
return "Person [name=" + name + ", age=" + age + "]";
}
}
复制代码
package objectinputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
public class ObjectStreamDemo {
public static void main(String[] args) throws IOException,
ClassNotFoundException {
File file = new File("object.txt");
Person p = new Person("marcojam", 26);
write(p, file);
System.out.println(read(file));
}
public static void write(Person p, File file) throws IOException {
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(
file));
oos.writeObject(p);
oos.close();
}
public static Object read(File file) throws IOException,
ClassNotFoundException {
ObjectInputStream ois = new ObjectInputStream(new FileInputStream(file));
Object obj = ois.readObject();
ois.close();
return obj;
}
}
复制代码
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2