对象流
以“对象”为数据源,但是必须将传输的对象进行序列化与反序列化操作。
与数据流相比,对象流能读写对象。
重点:Serializable接口、transient关键字
import java.io.*;
public class ObjectTest {
public static void main(String[] args) throws IOException, ClassNotFoundException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(new BufferedOutputStream(baos));
//序列化
oos.writeObject("玛卡巴卡");
oos.writeObject(new TheGarden("Makka",12));
oos.flush();
byte[] data = baos.toByteArray();
ObjectInputStream ois = new ObjectInputStream(new BufferedInputStream(new ByteArrayInputStream(data)));
//反序列化
Object str = ois.readObject();
Object gar = ois.readObject();
//避免出现类型转换错误
if (str instanceof String) {
str = (String) str;
System.out.println(str);
}
if (gar instanceof TheGarden){
gar = (TheGarden) gar;
System.out.println(((TheGarden) gar).getAge());
System.out.println(((TheGarden) gar).getName());
}
}
}
//自己写的类需要继承serializable接口,才能序列化
class TheGarden implements Serializable{
private String name;
private transient int age;
//transient关键字表示该数据不可序列化(隐藏该数据)
public String getName() {
return name;
}
public int getAge() {
return age;
}
public TheGarden(String name, int age) {
this.name = name;
this.age = age;
}
}