数据在本地文件的写入和读取

以基于Map接口的HashMap类的集合为 例

1、 判断文件是否存在

public void isRight(){                   //判断文件是否存在
        if(!myfile.exists()){
            try {
                myfile.createNewFile();  //不存在就要建立
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                System.out.println("文件已建立!");
            }
        }
    }

2、将集合里的对象存到文件

public void WriteFile(){
   for(int i=0;i<map.size();i++){                    // 一定要遍历
       try{
              fos = new FileOutputFile("Study.txt");
              oos = new ObjectOutPutStream(fos);
              oos.writeObject(map);

         }catch{

         }finaly{
             fos.close();
             oos.close();
         }
    }
}

3、将文件里的对象存入集合

public void readObject(){                //从文件中读取学生信息
         
            try {                         //  ② 为什么 读取不需要时不需要遍历?
                fis = new FileInputStream("Student.txt");
                if(myfile.length() == 0){
                    fis.close();
                    return ;
                }else{
                    ois = new ObjectInputStream(fis);
                    students = (HashMap<String, Student>) ois.readObject();
                    fis.close();
                    ois.close();
                    System.out.println("学生信息读取成功!");
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            
    }