Java序列化与反序列化(Serializable)

Java序列化与反序列化(Serializable)

特别注意:

1.要序列化的类必须实现Serializable借口

2.在反序列化(读取对象)的时候必须额外捕获EOFException

3.序列化之后的文件是“乱码”

 

 

package com.frank.io;

import java.io.EOFException;
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;
/**  
 * author:pengyan   
 * date:Jun 15, 2011   
 * file:ObjectInputOutputStreamTest.java  
 */ 

public class ObjectInputOutputStreamTest {
	String path="E:\\planda.p";
	public static void main(String[] args) throws Exception {
		ObjectInputOutputStreamTest test=new ObjectInputOutputStreamTest();
		test.outputObject();
		test.inputObject();
	}
	private void inputObject() throws Exception {
		//create inputObjectStream
		ObjectInputStream ois=new ObjectInputStream(new FileInputStream(path));
		// temp object to receive the value of this stream read everytime
		Object obj=null;
		PandaEntity p=null;
		try {
			while((obj=ois.readObject())!=null){
				p=(PandaEntity)obj;
				//show the object read by the stream
				System.out.println(p.toString());
			}
		} catch (EOFException e) {
			//throw EOFException when read end
			System.err.println("读取完毕");
		}
	}
	private void outputObject() throws Exception{
		//create two object to output
		PandaEntity p1=new PandaEntity(1000,"团团",3);
		PandaEntity p2=new PandaEntity(2000,"圆圆",3);
		//create the output stream
		ObjectOutputStream oos=new ObjectOutputStream(new FileOutputStream(path));
		//write object
		oos.writeObject(p1);
		oos.writeObject(p2);
		//flush the stream
		oos.flush();
		//close the stream
		oos.close();
	}
}
class PandaEntity implements Serializable{
	/*the class must implements Serializable interface
	 * or there will throw java.io.NotSerializableException 
	 * */
	private Integer id;
	private String name;
	private Integer age;
	@Override
	public String toString() {
		return "id:"+id+"\tname:"+name+"\tage:"+age;
	}
	public PandaEntity() {
	}
	public PandaEntity(Integer id, String name, Integer age) {
		this.id = id;
		this.name = name;
		this.age = age;
	}
	public Integer getId() {
		return id;
	}
	public void setId(Integer id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public Integer getAge() {
		return age;
	}
	public void setAge(Integer age) {
		this.age = age;
	}
}

 

你可能感兴趣的:(java)