【发布时间】:2015-01-29 14:32:57
【问题描述】:
我的 android 应用程序中有一个文本文件,其中包含一个 json。我需要阅读并解析那个json。文件大小为 21 MB。我正在使用以下代码读取文件:
StringBuilder stringBuilder = new StringBuilder();
InputStream input = getAssets().open(filename);
int size = input.available();
byte[] buffer = new byte[size];
byte[] tempBuffer = new byte[1024];
int tempBufferIndex = 0;
for(int i=0; i<size; i++){
if(i == 0){
tempBuffer[tempBufferIndex] = buffer[i];
}else{
int mod = 1024 % i;
if(mod == 0){
input.read(tempBuffer);
stringBuilder.append(new String(tempBuffer));
tempBufferIndex = 0;
}
tempBuffer[tempBufferIndex] = buffer[i];
}
}
input.close();
大小 int 在实际情况下是 20949874。循环完成后,即使我更改 for 循环的范围,stringBuilder 的长度也始终为 11264。我试图在不使用循环的情况下从 InputStream 创建一个字符串,但它总是给我 OutOfMemoryError 异常。我还在我的日志中得到“将堆(碎片情况)增加到 26.668MB 以分配 20949890 字节”。我在这里搜索并尝试了不同的解决方案,但没有成功。知道我应该如何解决这个问题。提前致谢。
【问题讨论】:
-
我可以推荐使用 gson
-
我认为您已经超出了应用程序专用的堆大小,请查看下面的 Suvitruf 答案。
-
是否有任何样本
标签: java android inputstream fileinputstream android-developer-api