gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:32:43 26 4
gpt4 key购买 nike

我正在 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com