问题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);
}
}
}