gpt4 book ai didi

java - 出现内存不足错误

转载 作者:行者123 更新时间:2023-12-01 17:34:49 26 4
gpt4 key购买 nike

我正在尝试将 12mb txt 文件作为 HashMap 加载到内存中,以供应用程序使用它,但我收到了 OutOfMemoryError

09-27 15:42:17.560: ERROR/AndroidRuntime(19030):     ... 11 more
09-27 15:42:17.560: ERROR/AndroidRuntime(19030): Caused by: java.lang.OutOfMemoryError
09-27 15:42:17.560: ERROR/AndroidRuntime(19030): at java.util.HashMap.makeTable(HashMap.java:559)
09-27 15:42:17.560: ERROR/AndroidRuntime(19030): at java.util.HashMap.doubleCapacity(HashMap.java:579)
09-27 15:42:17.560: ERROR/AndroidRuntime(19030): at java.util.HashMap.put(HashMap.java:409)
09-27 15:42:17.560: ERROR/AndroidRuntime(19030): at org.com.SentencesActivity.loadBigramFrequencies(SentencesActivity.java:151)
09-27 15:42:17.560: ERROR/AndroidRuntime(19030): at org.com.SentencesActivity.onClick(SentencesActivity.java:56)

有什么办法可以解决吗,还是dalvik vm的限制?

将文件加载到内存的代码:

public HashMap<String, Double> loadBigramFrequencies() throws IOException {
AssetManager assetManager = getAssets();

HashMap<String, Double> bigramFrequencies = new HashMap<String, Double>();
String[] splittedLine;
try {
// open the file for reading
InputStream instream = assetManager.open("bigramFrequencies.txt");

// if file the available for reading
if (instream != null) {
// prepare the file for reading
InputStreamReader inputreader = new InputStreamReader(instream);
BufferedReader buffreader = new BufferedReader(inputreader);

String line;

// read every line of the file into the line-variable, on line
// at the time
while ((line = buffreader.readLine()) != null) {
// do something with the settings from the file
splittedLine = line.split("\\#");
bigramFrequencies.put(splittedLine[0].trim(),
Double.parseDouble(splittedLine[1].trim()));
}
Log.v(LOG_TAG, "bigram frequencies loaded");

}

// close the file again
instream.close();

} catch (java.io.FileNotFoundException e) {
// do something if the myfilename.txt does not exits
}

return bigramFrequencies;
}

最佳答案

读取内存中的 12mb 文件会降低设备速度。对于普通电脑来说,12MB 听起来可能比较少,但大多数 Android 手机的 RAM 都少于 512MB。

您应该能够重新格式化文件或将其拆分,以便应用程序可以在需要时读取必要的部分。

此外,使用 SQLite Database可能更适合加快整个过程。

关于java - 出现内存不足错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7571331/

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