javaI/O中FileOut/InputStream借助ObjectOut/IntputStream写入和读取序列化之嵌套原理

一、FileOutputStream和ObjectOutputStream实现写入:
public static void main (String[] args){

      // Create an Employee object
      int[] days = {8, 10, 6, 8, 8};
      Employee emp = new Employee("Bill", 8.50, days);
try{
         FileOutputStream foStream = new FileOutputStream
("employee.dat") ;//在当前的项目下创建,dat为代码处理的data文件
        ObjectOutputStream ooStream = new ObjectOutputStream (foStream);
        ooStream.
writeObject (emp) ;//在用foStream初始化后 writeObject(emp), 将对象状态保存称序列化
                            // for(int i=0;i<5;i++) FileOutputStream 提供了write(byte b[]) write(int b)的方法
                         // foStream.write(days[i]);
        
foStream.flush();     //却是用foStream来强制输出和关闭
                                          //extends from OutputStream :force any buffered output bytes to written out
        
foStream.close();          //releases any system resources associated with this stream.
      }catch (Exception e){
         System.out.println ("Error during output: " + e.toString());
      }
}
二、FileInputStream和ObjectInputStream实现读出:
public static void main (String[] args){
Employee emp;
      try{
         FileInputStream fiStream = new FileInputStream ("employee.dat");
         ObjectInputStream oiStream = new ObjectInputStream (fiStream);
         emp = (Employee)
oiStream.readObject() ; //同样用ObjectInputStream方法实现 , 读取文件中对象还原称反序列化 
               //FileInputStream 只能read(byte b[])
       
  fiStream.close();   //用FileInputStream来关闭       //releases system resources associated with this stream.
         System.out.println (emp);/ /
Object类中指明类的toString碰到“println”之类的输出方法时会自动调用 ,不用显式打出来
      }catch (Exception e){
         System.out.println ("Error during input: " + e.toString());
      }
   }
总结: 1.FileOutputStream和ObjectOutputStream协作时,用FileOutputStream来处理文件;
2.再去初始化ObjectOutputStream,
使得ObjectOutputStream嵌套了FileOutputStream,
用来writeObject(obj)实现了到内存中的读取,而用FileOutputStream实现flush close与磁盘文件打交道。
因为两个对象指向同一个对象磁盘"employee.dat"引用(没有使用clone方法)。

3FileInputStream和ObjectInputStream也是同样的处理方式。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值