/*
对象流的使用
1.objectinputstream和objectoutputstream
2.作用:用于存储和读取基本数据类型数据或对象的处理流。他的强大之处就是可以把java中的对象写入到数据源中。也能把对象从数据源中还原回来
*/
public class ObjectInputOutputStream {
/*
序列化过程:将内存中的java对象保存到磁盘中或通过网络传输出去
使用ObjectOutPutStream实现
*/
@Test
public void test(){
ObjectOutputStream oos=null;
try {
//1.
oos=new ObjectOutputStream(new FileOutputStream(new File("object.bat")));
//2.
oos.writeObject(new String("我爱北京天安门"));
oos.flush();//刷新操作
}
catch (IOException e){
e.printStackTrace();
}
finally {
if(oos!=null)
try {
//3.
oos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
@Test
/*
反序列化:将磁盘文件中的对象还原为内存中的一个Java对象
使用ObjectInputStream
*/
public void test1(){
ObjectInputStream ois=null;
try {
ois=new ObjectInputStream(new FileInputStream(new File("object.bat")));
Object o = ois.readObject();
String str=(String) o;
System.out.println(str);
}
catch (IOException | ClassNotFoundException e){
e.printStackTrace();
}
finally {
if (ois!=null)
try {
ois.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}