现在的位置: 首页 > 综合 > 正文

黑马程序员-对象序列化与反序列化

2013年10月01日 ⁄ 综合 ⁄ 共 1795字 ⁄ 字号 评论关闭

需求:将多个对象序列化到一个文件中,并反序列化这些对象,打印出反序列化的信息

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
import java.util.List;

public class ObjectOutputStreamTest {

	/**
	 * 对象流演示
	 */
	public static void main(String[] args) {
		//文件输出流
		FileOutputStream fos = null;
		//对象序列化流
		ObjectOutputStream out = null;
		try {
			fos = new FileOutputStream("objectstream.txt");
			out = new ObjectOutputStream(fos);
			List<Person> pList = new ArrayList<Person>();
			pList.add(new Person("张三",25));
			pList.add(new Person("李四",31));
			pList.add(new Person("王五",29));
			for(Person p : pList){
				out.writeObject(p);
				out.flush();
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally{
			//关流
			try{
				if(null != fos)
					fos.close();
				if(null != out)
					out.close();
			}catch(IOException e){
				
			}
		}
	}

}

import java.io.EOFException;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.ObjectInputStream;

public class ObjectInputStreamTest {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		//文件输入流
		FileInputStream fis = null;
		//对象反序列化流
		ObjectInputStream in = null;
		try{
			//方法一:一个一个读取对象,但是太麻烦你,当一个文件中序列化的对象很多的话,
			//用这样的方法反序列化就不合适了
			/*fis = new FileInputStream("objectstream.txt");
			in = new ObjectInputStream(fis);
			//一个一个的读取流对象
			Person p1 = (Person)in.readObject();
			Person p2 = (Person)in.readObject();
			Person p3 = (Person)in.readObject();
			System.out.println(p1.getName() + ":" + p1.getAge());
			System.out.println(p2.getName() + ":" + p2.getAge());
			System.out.println(p3.getName() + ":" + p3.getAge());*/
			
			//方法二:循环读取,但是如果读完了,再接着读会报异常,我们在异常处理里面可以跳出循环
			fis = new FileInputStream("objectstream.txt");
			in = new ObjectInputStream(fis);
			Person p = null;
			while(true){
				
				try {
					p = (Person)in.readObject();
					System.out.println(p.getName() + ":" + p.getAge());
				} catch (EOFException e) {
					break;
					//e.printStackTrace();
				}
			}
		}catch(Exception e){
			e.printStackTrace();
		}finally{
			//关闭流
			try{
				if(null != fis){
					fis.close();
				}
				if(null != in){
					in.close();
				}
			}catch(IOException e){
				e.printStackTrace();
			}
		}
	}

}

抱歉!评论已关闭.