zoukankan      html  css  js  c++  java
  • 数据在本地文件的写入和读取

    以基于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();
                }
                
        }
  • 相关阅读:
    Linux命令:sed命令
    Linux命令:grep命令 | egrep命令
    Linux命令:find命令
    bash脚本编程
    Linux命令:vi | vim命令
    Linux文件权限管理
    237. 删除链表中的节点
    160. 相交链表
    538. 把二叉搜索树转换为累加树
    543.Diameter of Binary Tree
  • 原文地址:https://www.cnblogs.com/maxiaobao/p/5076840.html
Copyright © 2011-2022 走看看