对象流

public class Test {
	public static void main(String[] args) throws IOException {
		 File file = new File("cat.txt");
		//ObjectOutputStream 将 Java 对象的基本数据类型和图形写入 OutputStream
		ObjectOutputStream obOutput = null;
		
		//ObjectInputStream 对以前使用 ObjectOutputStream 写入的基本数据和对象进行反序列化
		ObjectInputStream obInput = null;
		Cat c3 = null;
	
		obOutput = new ObjectOutputStream(new FileOutputStream(file));
		obInput = new ObjectInputStream(new FileInputStream(file));
		Vector<Cat> ve = new Vector<Cat>();
		
		for(int i=0;i<5;i++){
			Cat c= new Cat("cat"+i,i*10);
			ve.add(c);
		}
		try {
			
			//writeObject 方法用于将对象写入流中
			for(int i=0;i<ve.size();i++){
				obOutput.writeObject((Cat)ve.get(i));
				
			}
			//刷新该流的缓冲。此操作将写入所有已缓冲的输出字节,并将它们刷新到底层流中
			obOutput.flush();  
			obOutput.close();
			for(int i=0;i<ve.size();i++){
				//readObject 方法用于从流读取对象
				 c3 = (Cat)obInput.readObject();
				 if(c3.year>20){
					 System.out.println("大猫"+c3.name+"----"+c3.year);
				 }else{
					 System.out.println(c3.name+"----"+c3.year);
				 }
				 
			}
			obInput.close();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
	}
}
class Cat implements Serializable{//在对象流中存储或恢复的所有类需实现Serializable
	private static final long serialVersionUID = 1L;
	String name;
	int year;
	public Cat(String name, int year) {
		super();
		this.name = name;
		this.year = year;
	}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值