黑马程序员技术交流社区

标题: IO流中一个小问题 [打印本页]

作者: 一帆风顺    时间: 2012-12-24 14:26
标题: IO流中一个小问题
本帖最后由 王博 于 2012-12-25 13:53 编辑

import java.io.*;
import java.util.*;
class  UnSerializaDate
{
         Date d = null;
         UnSerializaDate()
         {
              try
              {
                     FileInputStream f = new FileInputStream("date.ser");
                     //ObjectInputStream s = new ObjectInputStream(f);     //这俩步具体是什么意思啊?我直接调用f的read()也能读出来啊
                     //d = (Date)s.readObject();                                         //为什么要写这两步啊
                     f.read();
                     f.close();
              }
              catch (Exception e)
              {
                     e.printStackTrace();
              }
         }
         public static void main(String[] args)
         {
              UnSerializaDate a = new UnSerializaDate();
              System.out.println("the date read is:"+a.d);
         }
         
}

作者: 黄锦成    时间: 2012-12-24 16:57
//ObjectInputStream s = new ObjectInputStream(f);     //这俩步具体是什么意思啊?我直接调用f的read()也能读出来啊
//d = (Date)s.readObject();                                         //为什么要写这两步啊
这个是用于操作对象的字节流,这两句的作用的将文件中的数据读取出来,变成Date类型的对象
作者: sunalong    时间: 2013-7-10 11:35

//ObjectInputStream s = new ObjectInputStream(f);     //这俩步具体是什么意思啊?我直接调用f的read()也能读出来啊
//d = (Date)s.readObject();                                         //为什么要写这两步啊
d = (Date)s.readObject();   将字节流中的数据对象读取出来,强制转换为Date类型的,
下面的main函数里就用到了这个功能:System.out.println("the date read is:"+a.d);
这里你只用到了输出,感觉不到变成Date类型的作用了,假如你用Date里面的方法就感受到差别了:比如:
  1. import java.io.*;
  2. import java.util.*;
  3. class  UnSerializaDate
  4. {
  5.          Date d = null;
  6.          UnSerializaDate()
  7.          {
  8.               try
  9.               {
  10.                      FileInputStream f = new FileInputStream("date.ser");
  11.                      //ObjectInputStream s = new ObjectInputStream(f);     //这俩步具体是什么意思啊?我直接调用f的read()也能读出来啊
  12.                      //d = (Date)s.readObject();                                         //为什么要写这两步啊
  13.                      f.read();
  14.                      f.close();
  15.               }
  16.               catch (Exception e)
  17.               {
  18.                      e.printStackTrace();
  19.               }
  20.          }
  21.          public static void main(String[] args)
  22.          {
  23.               UnSerializaDate a = new UnSerializaDate();
  24.               System.out.println("the date read is:"+a.getHours());
  25.          }
  26.          
  27. }
复制代码

作者: sunalong    时间: 2013-7-10 11:36
上面的代码与你的区别在main函数中的第二行:
  1. System.out.println("the date read is:" + a.getHours());
复制代码





欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) 黑马程序员IT技术论坛 X3.2