【发布时间】:2011-09-18 12:32:45
【问题描述】:
我正在安卓上制作一个字典应用程序。在启动期间,应用程序将加载 .index 文件的内容(~2MB,100.000+ 行)
但是,当我使用 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释放了xxx个对象,其中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];
}
..它运行得非常快。但这并不是我想要的。
是否有任何解决方案可以像第二个 sn-p 一样快速运行并且像第一个一样易于使用?
注意。
【问题讨论】:
-
代码sn-p中
DataInputStream有什么用?看起来您不需要提取原始类型,只需要提取字符串?如果您知道Set的大小,有时预先分配大小会很有帮助,例如new HashSet<String>(100000) -
@Jeff Foster:感谢您关于分配 HashSet 大小的建议。
-
bugs.sun.com/bugdatabase/view_bug.do?bug_id=4513622 是答案所描述问题的好读物。
标签: java android dictionary io