java 将大型 JSON (InputStream) 放入 String 时出现内存不足错误
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5842201/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Out of memory error when putting large JSON (InputStream) to String
提问by DixieFlatline
I receive gziped JSON from web service and then i unzip it (size of unziped JSON is 3.2MB). I need to transform received InputStream to String so i can then create JSONObject and parse it. I do it with this code:
我从 Web 服务接收 gziped JSON,然后解压它(解压 JSON 的大小为 3.2MB)。我需要将接收到的 InputStream 转换为 String,这样我就可以创建 JSONObject 并解析它。我用这个代码来做:
public static String InputStreamToString(InputStream in)
throws IOException {
BufferedInputStream bis = new BufferedInputStream(in);
ByteArrayOutputStream buf = new ByteArrayOutputStream();
int result = bis.read();
while(result != -1) {
byte b = (byte)result;
buf.write(b);
result = bis.read();
}
return buf.toString();
}
I receive java.lang.OutOfMemoryError on the last line: "return buf.toString();" on the emulator and device with 288MB Ram.
我在最后一行收到 java.lang.OutOfMemoryError:“return buf.toString();” 在模拟器和具有 288MB Ram 的设备上。
What shall i do?
我该怎么办?
采纳答案by CommonsWare
Reading in a byte at a time is so1990's. Either use HttpClient and BasicResponseHandler
, or at least read the data in respectable chunksand append them using a StringBuilder
.
在同一时间在一个字节读是那么1990年的。要么使用 HttpClient and BasicResponseHandler
,要么至少以可观的块读取数据并使用StringBuilder
.
Assuming you are still having the problem, the issue is that there is no single block of memory that is big enough for your string, based upon other things your app has been doing. The Android garbage collector is not a compacting collector, so it is possible to have lots of free heap space yet not enough for a specific allocation request.
假设您仍然遇到问题,问题是根据您的应用程序一直在做的其他事情,没有足够大的内存块容纳您的字符串。Android 垃圾收集器不是压缩收集器,因此可能有大量空闲堆空间但不足以满足特定的分配请求。
In that case, you may need to switch to some sort of streaming JSON parser. If you happen to be targeting only Honeycomb and higher, you can use JSONReader
. Otherwise, Hymansonreportedly works on Android and apparently has a streaming mode.
在这种情况下,您可能需要切换到某种流式 JSON 解析器。如果您碰巧仅针对 Honeycomb 及更高版本,则可以使用JSONReader
. 否则,据报道Hyman逊在 Android 上工作并且显然有一个流媒体模式。
回答by sbridges
You can try to create a new JSONObject using
您可以尝试使用创建一个新的 JSONObject
new JSONObject(new JSONTokener(in))
instead of converting in to a String directly. However, this will probably only delay the problem. If you don't have enough memory to load a 3.2 meg string into memory, you probably won't have enough memory to load that as a json object, which will take more memory than the simple string.
而不是直接转换为字符串。但是,这可能只会延迟问题的出现。如果您没有足够的内存将 3.2 meg 字符串加载到内存中,则您可能没有足够的内存将其加载为 json 对象,这将比简单字符串占用更多内存。