向文件中存取对象,对象要实现序列化接口

来源:互联网 发布:海鹰数据 wish 编辑:程序博客网 时间:2024/06/06 11:49
packagecom.java.test;

importjava.io.BufferedInputStream;
importjava.io.BufferedOutputStream;
importjava.io.FileInputStream;
importjava.io.FileOutputStream;
importjava.io.IOException;
importjava.io.ObjectInputStream;
importjava.io.ObjectOutputStream;

publicclassTestObjectOutPutStream {
      /**
       * 向文件中写入一个对象,该对象在文件里是以二进制存放的.
       *@paramstudent
       */
      publicstaticvoidtestWriter(Studentstudent){
            try{
                  ObjectOutputStreamoos= new ObjectOutputStream( new BufferedOutputStream(newFileOutputStream("F://file.txt")));
                  oos.writeObject(student);
                  oos.flush();
                  oos.close();
                  
            }catch(IOExceptione) {
                  e.printStackTrace();
            }finally{
                  System.out.println("写入成功!");
            }
      }
      /**
       * 从文件中读取对象,并强制转换对象
       */
      publicstaticvoidtestReader(){
            
            try{
                  ObjectInputStreamois= new ObjectInputStream( new BufferedInputStream(newFileInputStream("F://file.txt")));
                  Studentstu= (Student)ois.readObject();
                  System.out.println(stu);
                  ois.close();
                  
            }catch(IOExceptione) {
                  //TODOAuto-generated catch block
                  e.printStackTrace();
            }catch(ClassNotFoundExceptione) {
                  //TODOAuto-generated catch block
                  e.printStackTrace();
            }finally{
                  System.out.println("读取成功!");
            }
      }
      
      
      publicstaticvoidmain(String[]args) {
            Studentstudent= new Student();
            student.setId(99);
            student.setName("maliao");
            student.setScore(899);
            
            testReader();
      }
      

}
0 0
原创粉丝点击