1

我有一个用一个外部方法扩展 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();
}

}

4

1 回答 1

2

您问题的先前版本中的“问号”很重要。它们表明您认为您看到的字符串实际上不是您正在使用的字符串。RandomAccessFile 是读取文本文件的糟糕选择。您可能正在阅读一个文本编码不是单字节的文本文件(也许是 utf-16)?由于 RandomAccessFile 进行“ascii”字符转换,因此生成的字符串被错误编码。这导致您的get()通话失败。

首先,找出文件的字符编码并使用适当配置的 InputStreamReader 打开它。

其次,扩展 TreeMap 是一个非常糟糕的设计。在这里使用聚合,而不是扩展。

于 2013-03-18T19:27:37.087 回答