我正在制作一款Android词典应用程序。在启动时,该应用程序将加载一个.index文件的内容(约2MB,100,000+行)。
然而,当我使用BufferedReader.readLine()并对返回的字符串进行操作时,该应用程序会导致OutOfMemory错误。
然而,当我使用BufferedReader.readLine()并对返回的字符串进行操作时,该应用程序会导致OutOfMemory错误。
// Read file snippet
Set<String> indexes = new HashSet<String)();
FileInputStream is = new FileInputStream(indexPath);
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
String readLine;
while ( (readLine = reader.readLine()) != null) {
indexes.add(extractHeadWord(readLine));
}
// And the extractHeadWord method
private String extractHeadWord(String string) {
String[] splitted = string.split("\\t");
return splitted[0];
}
在阅读日志时,我发现执行过程中会显式地多次触发GC清理对象(GC_EXPLICIT freed xxx objects,其中xxx是一个很大的数字,比如15000、20000等)。
我尝试了另一种方法:
final int BUFFER = 50;
char[] readChar = new char[BUFFER];
//.. construct BufferedReader
while (reader.read(readChar) != -1) {
indexes.add(new String(readChar));
readChar = new char[BUFFER];
}
它运行得非常快。但这并不是我想要的。
有没有一种解决方案既像第二个代码片段一样运行得快,又像第一个代码片段一样易于使用?
谢谢。
DataInputStream
有什么用处?看起来你只需要提取字符串而不是原始类型?如果你知道Set
的大小,预先分配空间可能会很有帮助,例如new HashSet<String>(100000)
。 - Jeff Foster