Java IO 对象的序列化与反序列化

package io.ObjectStream;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutput;
import java.io.ObjectOutputStream;

import io.p2.bean.Person;



public class ObjectStreamDemo {

	public static void main(String[] args) throws IOException, ClassNotFoundException {
//		writeObJ();//写对象 写到硬盘当  生命周期延长
		readObj();//读对象 必须有.object文件  和 .class文件
	}
	private static void readObj() throws IOException, ClassNotFoundException {
		ObjectInputStream ois=new ObjectInputStream(new FileInputStream("obj.object"));
		//对象的反序列化
		Person p=(Person)ois.readObject();
		System.out.println(p.getName()+":"+p.getAge());
		ois.close();
	}
	private static void writeObJ() throws IOException, IOException {
		ObjectOutputStream oos=new ObjectOutputStream(	new FileOutputStream("obj.object"));
		//对象序列化 被序列化的对象必须实现Serializable接口		
		oos.writeObject(new Person("xiaoqiang", 30));
		
		oos.close();
	}
	
}

你可能感兴趣的:(Java学习)