1、对象流主要的类有:ObjectInputStream和ObjectOutputStream
这两个流都是字节性质的流
2、保证对象的序列化:
1、当使用对象流写入或者读入对象时,要保证对象是序列化的
2、这是为了保证能把对象写入到文件,并能把对象正确读回到程序中来
3、如何实现序列化呢?
一个类如果实现了Serializable接口(JAVA.io包中的接口),那么这个类创建的对象就是所谓的序列化对象
4、序列化和反序列化:
1、序列化:把内存中的对象转换成可以进行网络传输或者磁盘存储的过程,叫序列化
2、反序列化:把文件中的二进制序列或者网络上读取一个数据装换成内存对象
5、代码实现:
1、序列化的实现:
package IO流之对象流;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
public class Test {
public static void main(String[] args) {
// 序列化的工作,如果要将多个对象序列化,可以使用ArrayList
//把内存中的对象转换成可以进行网络传输或者磁盘存储的过程,叫序列化
ObjectOutputStream oos=null;
try {
oos=new ObjectOutputStream(new FileOutputStream("D:\\young.txt"));
Hero hero=new Hero("我的父亲",200,300);
//把Hero对象通过序列化存储到磁盘上
oos.writeObject(hero);
oos.flush();
} catch (IOException e) {
e.printStackTrace();
}finally {
if(oos!=null) {
try {
oos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
//Serializable是一个非常特殊的接口,起到标记序列化的作用
class Hero implements Serializable{
String name;
double hp;
transient double mp;//被transient修饰的成员变量不能被序列化
public Hero(String name, double hp, double mp) {
super();
this.name = name;
this.hp = hp;
this.mp = mp;
}
@Override
public String toString() {
return “Hero [name=” + name + “, hp=” + hp + “, mp=” + mp + “]”;
}
}
2、反序列化的实现:
package IO流之对象流;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
public class Test1 {
public static void main(String[] args) {
//进行反序列化的过程:把文件中的二进制序列或者网络上读取一个数据装换成内存对象
ObjectInputStream ois=null;
try {
ois=new ObjectInputStream(new FileInputStream("D:\\young.txt"));
Object o=ois.readObject();//Hero是通过对象流读取而来的
if(o instanceof Hero) {
Hero h=(Hero)o;
System.out.println(h);
}
} catch (Exception e) {
e.printStackTrace();
}finally {
if(ois!=null) {
try {
ois.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}