内存不足的错误时,把大的JSON(的InputStream)为String错误、内存不足、JSON、InputStream

2023-09-04 23:52:04 作者:不可驯服

我收到来自Web服务gziped JSON,然后我把它解压(解压的JSON的大小3.2MB)。 我需要变换收到的InputStream字符串,这样我就可以创建的JSONObject并解析它。我做这个code:

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:

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();
}

我收到java.lang.OutOfMemoryError在最后一行:返回buf.toString();在仿真器和设备与288MB RAM。

I receive java.lang.OutOfMemoryError on the last line: "return buf.toString();" on the emulator and device with 288MB Ram.

我该怎么办?

推荐答案

在读的时间一字节的这样的1990年的。要么使用的HttpClient和 BasicResponseHandler ,或至少中读取数据尊敬块并使用它们附加一个的StringBuilder

Reading in a byte at a time is so 1990's. Either use HttpClient and BasicResponseHandler, or at least read the data in respectable chunks and append them using a 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.

在这种情况下,您可能需要切换到某种流JSON解析器。如果你碰巧只针对蜂窝和更高的,你可以使用JSONReader.否则,杰克逊据报道,适用于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, Jackson reportedly works on Android and apparently has a streaming mode.