JAVA I/0 练习8 序列化输入输出

问题1、创建一个Hero对象,设置其名称为garen。
把该对象序列化到一个文件garen.lol。
然后再通过序列化把该文件转换为一个Hero对象
问题2、准备一个长度是10,类型是Hero的数组,使用10个Hero对象初始化该数组

然后把该数组序列化到一个文件heros.lol

接着使用ObjectInputStream 读取该文件,并转换为Hero数组,验证该数组中的内容,是否和序列化之前一样

Hero类:

package pratice3;
import java.io.Serializable;
public class Hero implements Serializable{
	private static final long serialVersionUID = 1L;
    public String name;
    public float hp;
    Hero(){}
    Hero(String name,float hp){
    	this.name=name;
    	this.hp=hp;
    }
}

import pratice3.Hero;
/*序列化是使用ObjectOutputStream、ObjectInputStream输入输出的流操作*/
public class TestStream {
	//问题1
	public void oneHero()throws IOException, Exception{
		Hero hero=new Hero();
		hero.name="garen";
		hero.hp=600;
		//创建一个用于输出的流
		ObjectOutputStream out=new ObjectOutputStream(new FileOutputStream(new File("file21.lol")));
		out.writeObject(hero);
		//创建一个用于输入的流
		ObjectInputStream in =new ObjectInputStream(new FileInputStream(new File("file21.lol")));
		Hero h=(Hero)in.readObject();
		System.out.println(h.hp+h.name);
		return ;
	}
	//问题二
	//准备一个长度是10,类型是Hero的数组,使用10个Hero对象初始化该数组
	public static void main(String[] args) throws IOException, Exception{
		File file=new File("file22.lol");
		ObjectOutputStream out=new ObjectOutputStream(new FileOutputStream(file));
		for(int i=0;i<10;i++) {
			Hero h=new Hero(new String("hero"+i),600);
			out.writeObject(h);
		}
		ObjectInputStream in =new ObjectInputStream(new FileInputStream(file));
		for(int i=0;i<10;i++) {
			Hero h=(Hero)in.readObject();
			System.out.println(h.hp+" "+h.name);
		}
	}
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值