java - Android - 读取文本文件时内存不足

标签 java android dictionary io

我正在 Android 上制作字典应用程序。在启动期间,该应用程序将加载 .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 freeed 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];
}

..而且它运行得非常快。但这并不是我想要的。

是否有任何解决方案可以像第二个 fragment 一样快速运行并且像第一个 fragment 一样易于使用?

关注。

最佳答案

extractHeadWord 使用 String.split方法。此方法不会创建新字符串,而是依赖于底层字符串(在您的例子中是 line 对象)并使用索引来指出"new"字符串。

因为您对字符串的其余部分不感兴趣,您需要丢弃它以便它被垃圾收集,否则整个字符串将在内存中(但您只使用它的一部分)。

调用构造函数String(String) (“复制构造函数”)丢弃字符串的其余部分:

private String extractHeadWord(String string) {
    String[] splitted = string.split("\\t");
    return new String(splitted[0]);
}

关于java - Android - 读取文本文件时内存不足,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6408776/

相关文章:

java - 获取字符串的一部分

c# - 如何将键值对转换为自定义对象列表

dictionary - 如何将值插入嵌套 Swift 字典

java - `AnnotationConfigNonEmbeddedWebApplicationContext` 还没有刷新

java - 从获得许可开始 fragment

java - 运行项目或构建 apk 时出错

php - 如何在corona sdk应用程序中显示用户名

android - 是否可以有 xml-land 资源文件夹?

android - 如何下载受 NTLM 身份验证保护的文件

c++ - 为 std::map 定义一个使用值而不是键的比较函数