利用HashMap存取对象

来源:互联网 发布:base64解码 js 编辑:程序博客网 时间:2024/05/23 01:20

1.HashMap 已实现的接口

Serializable, Cloneable, Map<K,V>

2.方法摘要

 

相关代码(Customer 类)

/**     *      * @param ha     *            write(HashMap<String,Customer> ha) 传来HashMap对象列表 将对象写入文件中     */    public static void write(HashMap<String, Customer> ha) {        ;        try {            ObjectOutputStream oos = new ObjectOutputStream(                    new FileOutputStream("e:/db/db.dat"));            oos.writeObject(ha);            oos.close();        } catch (FileNotFoundException e) {                   e.printStackTrace();        } catch (IOException e) {                  e.printStackTrace();        }    }    /**     * @param id     * @return ReadCustomer(String id) 方法 通过HashMap 关键字 读取对象 并且返回对象     */    public static Customer readCustomer(String mark) {        HashMap<String, Customer> hm = new HashMap<String, Customer>();        Customer c = new Customer();        try {            ObjectInputStream ois = new ObjectInputStream(new FileInputStream(                    "e:/db/db.dat"));            hm = (HashMap<String, Customer>) ois.readObject();            c = hm.get(mark);            ois.close();        } catch (FileNotFoundException e) {                      e.printStackTrace();        } catch (IOException e) {                        e.printStackTrace();        } catch (ClassNotFoundException e) {                      e.printStackTrace();        }        return c;    }/**     * writeCustomer(Customer cus) 将对象写入HashMap 列表中并通过write()方法将对象写入文件中     *      * @param account     */    public static void writeCustomer(Customer cus) {        HashMap<String, Customer> m = new HashMap<String, Customer>();        try {            ObjectInputStream ois = new ObjectInputStream(new FileInputStream(                    "e:db/db.dat"));            m = (HashMap<String, Customer>) ois.readObject();            m.put(cus.getMark(), cus);            write(m);            ois.close();        } catch (FileNotFoundException e) {            e.printStackTrace();        } catch (IOException e) {            e.printStackTrace();        } catch (ClassNotFoundException e) {            e.printStackTrace();        }        Util.stay();    }


                                             
0 0