读书人

javaI/O中FileOut/InputStream凭借Obj

发布时间: 2012-11-10 10:48:50 作者: rapoo

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也是同样的处理方式。

读书人网 >网络基础

热点推荐