使用ObjectOutputStream创建位置文件

时间:2014-07-24 05:12:53

标签: java objectoutputstream

我有一个HashMap,我存储了多个源的上次读取时间,我需要将其备份到文件中。相同的散列映射会定期更新,并且每次都应该备份。

我正在使用ObjectOutputStream,因为同一个对象已更新,我在ObjectOutputStream上执行了reset(),因此文件已更新,但是这样可以看到每个writeObject()个新行被写入文件应该是因为该对象被附加到文件中。我的服务是长期运行的服务,所以我无法承受每次都要追加的对象,因为这会导致文件变得庞大。

以下是我的代码片段

public void open() throws WCException {
    try {
        ObjectInputStream objectInputStream = new ObjectInputStream(new FileInputStream(bookmarkFile));

        bookmarks = (HashMap<String, Long>) objectInputStream.readObject();

        objectInputStream.close();
    } catch (ClassNotFoundException | IOException e) {
    }

    try {
        fileOutputStream = new FileOutputStream(bookmarkFile);
        objectOutputStream = new ObjectOutputStream(fileOutputStream);
    } catch (IOException e) {
        throw new WCException("Bookmarker", e.getCause());
    }
}

public void close() throws WCException {
    try {
        objectOutputStream.close();
        fileOutputStream.close();
    } catch (IOException e) {
        throw new WCException("Bookmarker", e.getCause());
    }
}

public synchronized void write() throws WCException {
    try {
        objectOutputStream.writeObject(bookmarks);
        objectOutputStream.reset();
    } catch (IOException e) {
        throw new WCException("Bookmarker", e.getCause());
    }
}

public synchronized void update(HashMap<String, Long> bookmark) {
    for (Map.Entry<String, Long> entry : bookmark.entrySet()) {
        if (!bookmarks.containsKey(entry.getKey()))
            bookmarks.put(entry.getKey(), entry.getValue());
        else {
            long last = bookmarks.get(entry.getKey());
            if (last < entry.getValue())
                bookmarks.put(entry.getKey(), entry.getValue());
        }
    }
}

我想要一些文件中总有一个简单对象的东西,这是最新的。我甚至可以离开ObjectOutputStream。

0 个答案:

没有答案