java对象数组的文件存取

来源:互联网 发布:海鹰数据 wish 编辑:程序博客网 时间:2024/06/06 09:01
万物接对象所以数组也是一个对象,可以直接写入;

packagecom.java.test;

importjava.io.BufferedInputStream;
importjava.io.BufferedOutputStream;
importjava.io.FileInputStream;
importjava.io.FileOutputStream;
importjava.io.IOException;
importjava.io.ObjectInputStream;
importjava.io.ObjectOutputStream;
importjava.util.ArrayList;
importjava.util.List;

/**
 * 测试向本地文件存储及读取对象数组
 *@authorAdministrator
 * 2015年11月4日16:00:22
 *
 */
publicclassTestListObject {
      /**
       * 建立一个学生对象的数组
       *@paramstu
       *@return
       */
      publicstaticList<Student> listStudents(Studentstu){
            List<Student>lists= new ArrayList<Student>();
            for( int i = 0;i<10;i++) {
                  lists.add(stu);
            }
            return lists;
      }
      /**
       * 将student对象数组写入到文件中,数组也是一个对象,所以可以直接使用对象流存到文件中
       *@paramstus
       */
      publicstaticvoidwriteIntoFile(List<Student>stus){
            ObjectOutputStreamoos;
            try{
                  oos= new ObjectOutputStream( new BufferedOutputStream(newFileOutputStream("F://file.txt")));
                  
                  oos.writeObject(stus);
                  
                  oos.flush();
                  oos.close();      
            }catch(IOExceptione) {
                  //TODOAuto-generated catch block
                  e.printStackTrace();
            }finally{
                  System.out.println("文件写入完成!");
            }
      }
      /**
       * 从文件中读取对象数组,并强制转换对象
       */
      @SuppressWarnings("unchecked")
      publicstaticList<Student> testReader(){
            List<Student>lists= null;
            try{
                  ObjectInputStreamois= new ObjectInputStream( new BufferedInputStream(newFileInputStream("F://file.txt")));
                  lists=(ArrayList<Student>)ois.readObject();
                  ois.close();
            }catch(IOExceptione) {
                  //TODOAuto-generated catch block
                  e.printStackTrace();
            }catch(ClassNotFoundExceptione) {
                  //TODOAuto-generated catch block
                  e.printStackTrace();
            }finally{
                  System.out.println("读取成功!");
            }
            returnlists;
      }
      publicstaticvoidmain(String[]args) {
            Studentstudent= new Student();
            student.setId(99);
            student.setName("maliao");
            student.setScore(899);
            
            //List<Student>stus = listStudents(student);
            //writeIntoFile(stus);
            System.out.println(testReader());
            
      }

}
0 0
原创粉丝点击