设为首页 加入收藏

TOP

利用ObjectInputStream和ObjectOutputStream实现对象的序列化
2015-07-24 06:28:44 来源: 作者: 【 】 浏览:32
Tags:利用 ObjectInputStream ObjectOutputStream 实现 对象 序列化
package cn.felay.io;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
/**
 * 对象的持久化
 * @author felayman
 * @timer 2014年6月10日 下午6:37:16
 */
public class ObjectInputStreamDemo {

	public static void main(String[] args) {
		
		
		ObjectInputStream in = null;
		ObjectOutputStream out = null;

		try {
			out = new ObjectOutputStream(new FileOutputStream(
					"src/res/student.dat"));
			out.writeObject(new Student(1, "方", "磊"));
			out.writeObject(new Student(2, "刘", "欢"));
			out.writeObject(new Student(3, "宗", "阳"));
			in = new ObjectInputStream(new FileInputStream(
					"src/res/student.dat"));
			for (int i = 0; i < 3; i++) {
				System.out.println(in.readObject().toString());
			}
		} catch (IOException e) {
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} finally {
			try {
				out.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
			try {
				in.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}

	}

}

class Student implements Serializable {

	private static final long serialVersionUID = 5987036960278879461L;

	private int id;

	public int getId() {
		return this.id;
	}

	public void setId(int id) {
		this.id = id;
	}

	public String getFirstName() {
		return this.firstName;
	}

	public void setFirstName(String firstName) {
		this.firstName = firstName;
	}

	public String getLastName() {
		return this.lastName;
	}

	public void setLastName(String lastName) {
		this.lastName = lastName;
	}

	private String firstName;

	public Student(int id, String firstName, String lastName) {
		super();
		this.id = id;
		this.firstName = firstName;
		this.lastName = lastName;
	}

	private String lastName;

	@Override
	public String toString() {
		return "ID:" + this.id + " " + this.firstName + " " + this.lastName;
	}

}

】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇XTU OJ 1210 Happy Number (暴力+.. 下一篇HDU 1556 Color the Ball 线段树 ..

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容: