首页

关于java如何实现对象序列化在磁盘上的存取操作?

标签:java,java基础,序列化,ObjectOutputStream,ObjectInputStream     发布时间:2015-06-15   

前言

java中对象序列化过程分为序列化和反序列化两个部分,具体参见“对象序列化及反序列化意义及实现方法有哪些?”。序列化将数据分解成字节流,以便存储在文件或在网络上传输。反序列化从字节流或者网络通过字节流重新还原对象。

代码示例

1.向文件写入序列化对象

public class writeTo{@b@    @b@    public static void main(String[] args){@b@        writeTo w=new writeTo();@b@        try{@b@            e.write();@b@        }catch(IOException e){@b@            e.printStackTrace();@b@        }@b@    }@b@    @b@    puhlic void  write() throws  IOException{@b@        @b@        FileOutputStream fos=new FileOutputStream("c:/store.txt");@b@        ObjectOutputStream oos=new ObjectOutputStream(fos);@b@        oos.writeObject("test");@b@        oos.writeObject(new Date());@b@        oos.flush();@b@   @b@    }@b@    @b@}

2.从文件中读取序列化对象

public class readBy{@b@@b@    public static void main(String[] args){@b@      readBy r=new readBy();@b@      try{@b@          e.read();@b@      }catch(IOExcepion e){@b@          e.printStackTrace();@b@      }catch(ClassNotFoundException e1){@b@          e1.printStackTrace();@b@      }@b@    }@b@    @b@    public void read() throws IOExcepiton,ClassNotFoundException{@b@        @b@        FileInputStream fis=new FileInputStream("c:/store.txt");@b@        ObjectInputStream ois=new ObjectInputStream(fis);@b@        String s1=(String)ois.readObject();@b@        Date d=(Date)ois.readObject();@b@    }@b@    @b@}