67

package com.haizhitao.io3;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;

public class SerializableTest1
{
	public static void main(String[] args) throws Exception
	{
		Person p1 = new Person(29, "zhangsan", 2.13);
		Person p2 = new Person(24, "lisi", 3.56);
		Person p3 = new Person(14, "wangwu", 5.34);
		
		//将Person对象序列化到文件中
		FileOutputStream fos = new FileOutputStream("c:/serializable.txt");
		
		ObjectOutputStream oos = new ObjectOutputStream(fos);
		
		oos.writeObject(p1);
		oos.writeObject(p2);
		oos.writeObject(p3);
		
		oos.close();
		
		//再将Person对象反序列化到内存当中,打印出来
		FileInputStream fis = new FileInputStream("c:/serializable.txt");
		
		ObjectInputStream ois = new ObjectInputStream(fis);
		
		Person p = null;
		
		for(int i = 0; i < 3; i++)
		{
			p = (Person)ois.readObject();
			
			System.out.println(p.age + ", " + p.name + ", " + p.height);
		}
		
		ois.close();
	}
}

class Person implements Serializable
{
	int age;
	String name;
	double height;
	
	public Person(int age, String name, double height)
	{
		this.age = age;
		this.name = name;
		this.height = height;
	}
}

//output:
//	29, zhangsan, 2.13
//	24, lisi, 3.56
//	14, wangwu, 5.34

阅读更多
博主设置当前文章不允许评论。

没有更多推荐了,返回首页