对象流的读入与写出

对象流的读入与写出的简单应用

需要注意的事情:

1.用对象流写的对象必须要实现Serializable接口----贴标签技术

2.对象流的读取必须采用捕捉异常的方式控制结束,不能采用available()>0

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

import org.junit.Test;

public class ObjectStrean {
	@Test
	public void testObjWrite() {
		ObjectOutputStream out = null;
		try {
			// 后序可以随便
			out = new ObjectOutputStream(new FileOutputStream("E:/test/person.ppp"));
			for (int i = 0; i < 5; i++) {
				Person person = new Person("nn" + i, 10 + i);
				out.writeObject(person);
			}
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (out != null) {
				try {
					out.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}

	@Test
	public void testIn() {
		ObjectInputStream in = null;
		try {
			in = new ObjectInputStream(new FileInputStream("E:/test/person.ppp"));
			// while(in.available()>0){//读取对象流不能使用available
			while (true) {
				Person person = (Person) in.readObject();
				System.out.println(person);
			}
		} catch (EOFException e) {
			System.out.println("Over!");
		} catch (IOException e) {
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
	}
}

// 对象流的读取对象必须实现序列化接口
class Person implements Serializable {
	private static final long serialVersionUID = 1L;
	String name;
	int age;

	public Person(String name, int age) {
		super();
		this.name = name;
		this.age = age;
	}

	public Person() {
		super();
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public int getAge() {
		return age;
	}

	public void setAge(int age) {
		this.age = age;
	}

	@Override
	public String toString() {
		return name + "," + age;
	}

}


  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值