2013-03-18 67 views
1

我有一个使用一种外部方法扩展TreeMap的类。 外部方法“打开”假设以下面的格式“word:meaning”从给定的文件中读取行并将其添加到TreeMap中 - put(“word”,“meaning”)。即使密钥存在,Java TreeMap <String,String>也会返回null

所以我阅读RandomAccessFile的文件并把钥匙值树形图,当我打印树形图中,我可以看到正确的键和值,例如:

{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(); 
} 

}

+5

为了更好地提供帮助,请发布[SSCCE](http://sscce.org/)。不要包括sigs。在问题中,它们是噪音。这个问题在键/值的文本中有一些非常奇怪的字符。 – 2013-03-18 19:06:10

+0

请提供一个说明您的问题的最小,完整的例子。 – 2013-03-18 19:08:10

+0

{ A A A A= B B B B, C A B= y a h o o !} ..这是什么? – 2013-03-18 19:10:41

回答

2

从以前版本的问题的 “问号” 是很重要的。他们表示你认为你所看到的琴弦并不是你正在使用的琴弦。 RandomAccessFile是阅读文本文件的糟糕选择。你大概是阅读一个文本文件的文本编码是而不是单字节(UTF-16也许)?由于RandomAccessFile执行“ascii”字符转换,所以产生的字符串会被错误编码。这导致您的get()调用失败。

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

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

相关问题