对象流指的是可以直接把一个对象以流的形式传输给其他的介质,比如硬盘
一个对象以流的形式进行传输,叫做序列化。 该对象所对应的类,必须是实现Serializable接口
1,序列化一个对象
创建一个Hero对象,设置其名称为garen。
把该对象序列化到一个文件garen.lol。
然后再通过序列化把该文件转换为一个Hero对象
注意:把一个对象序列化有一个前提是:这个对象的类,必须实现了Serializable接口
import java.io.Serializable;
public class Hero implements Serializable{
// 表示这个类当前的版本,如果有了变化,比如新设计了属性,就应该修改这个版本号
private static final long serialVersionUID = 1L;
public String name;
public float hp;
}
public class AtWill {
public static void main(String[] args) {
//创建一个Hero garen
//要把Hero对象直接保存在文件上,务必让Hero类实现Serializable接口
Hero h = new Hero();
h.name = "garen";
h.hp = 616;
//准备一个文件用于保存该对象
File f = new File("H:\\码云project\\gogo\\garen.lol");
try(
//创建对象输出流
FileOutputStream fos = new FileOutputStream(f);
ObjectOutputStream oos = new ObjectOutputStream(fos);
//创建对象输入流
FileInputStream fis = new FileInputStream(f);
ObjectInputStream ois = new ObjectInputStream(fis);
) {
oos.writeObject(h);
Hero h2 = (Hero)ois.readObject();
System.out.println(h2.name);
System.out.println(h2.hp);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
在本地打开文件H:\\码云project\\gogo\\garen.lol,看到的是序列化后的内容
2,练习-序列化数组
准备一个长度是10,类型是Hero的数组,使用10个Hero对象初始化该数组
然后把该数组序列化到一个文件heros.lol
接着使用ObjectInputStream 读取该文件,并转换为Hero数组,验证该数组中的内容,是否和序列化之前一样
public class AtWill {
public static void main(String[] args) {
//创建一个Hero garen
//要把Hero对象直接保存在文件上,务必让Hero类实现Serializable接口
Hero[] heros = new Hero[10];
for (int i = 0; i < heros.length; i++) {
Hero hero = new Hero();
hero.name = "hero"+i;
hero.hp = i;
heros[i] = hero;
}
//准备一个文件用于保存该对象
File f = new File("H:\\码云project\\gogo\\garen.lol");
try(
//创建对象输出流
FileOutputStream fos = new FileOutputStream(f);
ObjectOutputStream oos = new ObjectOutputStream(fos);
//创建对象输入流
FileInputStream fis = new FileInputStream(f);
ObjectInputStream ois = new ObjectInputStream(fis);
) {
oos.writeObject(heros);
Hero[] heros2 = (Hero[])ois.readObject();
for (int i = 0; i < heros.length; i++) {
System.out.println(heros2[i].name);
System.out.println(heros2[i].hp);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
参考来源于:
http://how2j.cn/k/io/io-objectstream/351.html?p=48616