我得到一个文件personHashMap.ser
,里面有一个哈希图。这是我如何创建它的代码:
String file_path = ("//releasearea/ToolReleaseArea/user/personHashMap.ser");
public void createFile(Map<String, String> newContent) {
try{
File file = new File(file_path);
FileOutputStream fos=new FileOutputStream(file);
ObjectOutputStream oos=new ObjectOutputStream(fos);
oos.writeObject(newContent);
oos.flush();
oos.close();
fos.close();
}catch (Exception e){
System.err.println("Error in FileWrite: " + e.getMessage());
}
}
现在,我希望,当程序运行时,所有五分钟都仅使用更改的内容personHashMap.ser
更新文件。所以我调用的方法:
public void updateFile(Map<String, String> newContent) {
Map<String, String> oldLdapContent = readFile();
if(!oldLdapContent.equals(ldapContent)){ // they arent the same,
// so i must update the file
}
}
但是现在我没有任何想法如何实现这一点。
仅更新新内容对性能更好,还是应该清理完整文件并再次插入新列表?
希望你能帮助我..
编辑:
HashMap 包括 即 street=Example Street
.
但是现在,新街叫New Example Street
.现在我必须更新文件中的哈希图。所以我不能只是附加新内容...
首先,HashMap
并不是一个合适的选择。它专为内存使用而设计,而不是序列化(当然,它可以以标准方式序列化)。但如果它只有 2kb,那么继续编写整个内容而不是更新的数据。
其次,您似乎过于担心这种相当微不足道的方法的性能(对于2kb,写入只需几毫秒)。我会更担心一致性和并发性问题。我建议你考虑使用轻量级数据库,如JavaDB或h2。
使用构造函数FileOutputStream(File file, boolean append)
,将boolean append
设置为 true
。它将在现有文件中追加文本。
可以在循环中调用 updateFile 方法,然后调用睡眠 5 分钟(5*60*1000 毫秒)。
Thread.Sleep(300000); // sleep for 5 minutes
要附加到您现有的文件,您可以使用:
FileOutputStream fooStream = new FileOutputStream(file, true);