我正在处理一个字典应用程序,该应用程序从文本文件中读取单词,但文本文件的大小为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;
}
答案 0 :(得分:0)
可以使用 gzip 单文件压缩(“big-text.txt.gz”),并使用GZipInputStream。
相同的String应该在内存中保存一次。在需要时,在传递字符串之前,您可以搜索它:
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;
}
使用数据库的建议也很好。