gpt4 book ai didi

java - 在 Android 应用程序中读取 10mb 大文本文件

转载 作者:行者123 更新时间:2023-12-01 04:50:05 24 4
gpt4 key购买 nike

我正在开发一个字典应用程序,它从文本文件中读取单词,但文本文件的大小为 10mb,因此由于内存限制,我无法在模拟器或设备上运行它。

那么这个问题的解决办法是什么呢?我可以在压缩时从 zip 中读取文本文件吗?还是将其拆分为 10 个单独的文本文件(每个文件 1mb)更好?

下面是当前读取文本文件的代码,我需要对代码进行哪些更改?

private synchronized void loadWords(Resources resources) throws IOException {
if (mLoaded) return;

Log.d("dict", "loading words");
InputStream inputStream = resources.openRawResource(R.raw.definitions);
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));

try {
String line;
while((line = reader.readLine()) != null) {
String[] strings = TextUtils.split(line, ":");
if (strings.length < 2) continue;
addWord(strings[0].trim(), strings[1].trim());
}
} finally {
reader.close();
}
mLoaded = true;
}

public synchronized List<Word> getAllMatches(Resources resources) throws IOException {
List<Word> list = new ArrayList<Word>();
InputStream inputStream = resources.openRawResource(R.raw.definitions);
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));

try {
String line;
while((line = reader.readLine()) != null) {
String[] strings = TextUtils.split(line, ":");
if (strings.length < 2) continue;
Word word = new Word(strings[0].trim(), strings[1].trim());
list.add(word);
}
} finally {
reader.close();
}

return list;
}

最佳答案

可以使用gzip单文件压缩(“big-text.txt.gz”),并使用GZipInputStream。

同一个字符串应该在内存中保留一次。如果需要,在传递字符串之前,您可以搜索它:

Map<String, String> sharedStrings = new HashMap<>();

String share(String s) {
String sToo = sharedStrings.get(s);
if (sToo == null) {
sToo = s;
sharedStrings.put(s, s);
}
return sToo;
}

使用数据库的建议也是一个很好的建议。

关于java - 在 Android 应用程序中读取 10mb 大文本文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15134248/

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