在java中编写,读取和删除对象到文件中

时间:2014-10-27 00:11:00

标签: java object file-io objectinputstream

我希望将对象列表写入文件,然后逐个读取,并分别删除。 写作和阅读功能如下。对于逐个读取,首先我读取所有,然后先弹出,然后再写入文件。它非常无效,需要很长时间。那么,我该怎么做才能获得更好的性能?或许,还有其他变种来解决这个问题

  public void writeToDisk(String filePath,TreeMap<String, ArrayList<Integer>> obj){
    File file = new File(filePath);
    FileOutputStream fout = null;
    try {
        fout = new FileOutputStream(file);
        ObjectOutputStream o = new ObjectOutputStream(fout);
        o.writeObject(obj);
        o.close();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

public TreeMap<String, ArrayList<Integer>> readFromDisk(String filePath){
    TreeMap<String,ArrayList<Integer>> invertIndexMap = null;
    File file = new File(filePath);
    FileInputStream f;
    try {
        f = new FileInputStream(file);
        ObjectInputStream s = new ObjectInputStream(f);
        invertIndexMap = (TreeMap<String, ArrayList<Integer>>) s.readObject();
        s.close();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (ClassNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return invertIndexMap;
}

0 个答案:

没有答案