我有一个用一个外部方法扩展 TreeMap 的类。外部方法“open”假设从给定文件中读取以下格式“word:meaning”的行并将其添加到 TreeMap - put(“word”, “meaning”)。
所以我用 RandomAccessFile 读取文件并将键值放在 TreeMap 中,当我打印 TreeMap 时,我可以看到正确的键和值,例如:
{AAAA=BBBB, CAB=yahoo!}
但是由于某种原因,当我得到(“AAAA”)时,我得到了空值。
它发生的任何原因以及如何解决它?
这是代码
public class InMemoryDictionary extends TreeMap<String, String> implements
PersistentDictionary {
private static final long serialVersionUID = 1L; // (because we're extending
// a serializable class)
private File dictFile;
public InMemoryDictionary(File dictFile) {
super();
this.dictFile = dictFile;
}
@Override
public void open() throws IOException {
clear();
RandomAccessFile file = new RandomAccessFile(dictFile, "rw");
file.seek(0);
String line;
while (null != (line = file.readLine())) {
int firstColon = line.indexOf(":");
put(line.substring(0, firstColon - 1),
line.substring(firstColon + 1, line.length() - 1));
}
file.close();
}
@Override
public void close() throws IOException {
dictFile.delete();
RandomAccessFile file = new RandomAccessFile(dictFile, "rw");
file.seek(0);
for (Map.Entry<String, String> entry : entrySet()) {
file.writeChars(entry.getKey() + ":" + entry.getValue() + "\n");
}
file.close();
}
}