JAVA中序列化和反序列化

一般程序在运行时,产生对象,这些对象随着程序的停止运行而消失(java回收机制)
但如果我们想把某些对象(因为是对象,所以有各自不同的特性)保存下来,
在程序终止运行后,这些对象仍然存在,可以在程序再次运行时读取这些对象的值,
或者在其他程序中利用这些保存下来的对象。这种情况下就要用到对象的序列化。

对象序列化的最主要的用处就是在传递,和保存对象(object)的时候,保证对象的完整性和可传递性。
如通过网络传输,或者把一个对象保存成一个文件的时候,要实现序列化接口

implements Serializable就是用来标识这个类的对象可以被序列化,如果不标识,则不可序列化。

public class Pig implements Serializable {
private String name;

//属性前加了transient,表示序列化时不会被写到文件中,序列化时把它忽略
transient private int price;
private int age;
public Pig() {
super();
}
public Pig(String name, int price, int age) {
super();
this.name = name;
this.price = price;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getPrice() {
return price;
}
public void setPrice(int price) {
this.price = price;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}

//测试类

public class Test {
public static void main(String[] args) throws Exception{
Pig p=new Pig("猪坚强", 2000, 6);
//序列化 对象---文件
FileOutputStream os=new FileOutputStream("d:/pig.dat");
//转成对象流
ObjectOutputStream oos=new ObjectOutputStream(os);
oos.writeObject(p);
oos.close();
os.close();

//反序列化 文件---对象
FileInputStream is=new FileInputStream("d:/pig.dat");
//转成对象流
ObjectInputStream ois=new ObjectInputStream(is);
Pig p1=(Pig)ois.readObject();
System.out.println(p1.getName()+"\t"+p1.getPrice()+"\t"+p1.getAge());
}
}

 

 

posted @ 2014-04-08 20:43  莫名字  阅读(223)  评论(0编辑  收藏  举报