简体   繁体   English

Android StringBuilder内存不足,带有大型XML文件

[英]Android StringBuilder out of memory with large XML file

I'm using a soap service on android device and as response I get 7mb file from server. 我在Android设备上使用了肥皂服务,并且作为响应,我从服务器获取了7mb文件。 This causes my app to crash with out of memory error when converting input stream to string. 将输入流转换为字符串时,这会导致我的应用崩溃并出现内存不足错误。 MemoryAnalyzer shows that memory was allocated to StreamBuilder. MemoryAnalyzer显示内存已分配给StreamBuilder。 What is the best way to deal with such big responses? 处理如此巨大反应的最佳方法是什么?

HttpEntity entity = new StringEntity(soap.toString());
httppost.setEntity(entity);
HttpResponse response = httpclient.execute(httppost);
HttpEntity r_entity = response.getEntity();
if( r_entity != null ) {
   result = inputStreamToString(r_entity.getContent());
}
...
//convert stream to string
public static String inputStreamToString(InputStream stream) throws IOException {
    BufferedReader br = new BufferedReader(new InputStreamReader(stream));
    StringBuilder sb = new StringBuilder();
    String line = null;
    while ((line = br.readLine()) != null) {
          sb.append(line + "\n");
    }
    br.close();
    return sb.toString();
}

The most obvious answer is to use streams and parse the result as it comes. 最明显的答案是使用流并解析结果。 If it's an XML file you're parsing then SAX is probably the best avenue for you. 如果您要解析的是XML文件,那么SAX可能是您的最佳途径。

StringBuilder requires twice as much memory as it has data at the time of expansion. StringBuilder需要的内存是扩展时的两倍。 A new, larger (almost for sure larger than required) array of chars will be allocated and a copy will be made, only then the old array can be discarded. 将分配一个新的,更大的(几乎肯定大于所需的)字符数组,并进行复制,然后才可以丢弃旧的数组。

Collect all lines into ArrayList<String> that is cheaper to grow, just a size of String reference per line. 将所有行收集到更便宜的ArrayList<String> ,每行只有String引用的大小。 After you finish reading, you can count exact length in a loop and allocate StringBuilder of exactly required size. 阅读完之后,您可以在一个循环中计算确切的长度,并分配恰好需要的大小的StringBuilder。 Close the stream first. 首先关闭流。 Or, maybe you can reuse the list directly without converting into string. 或者,也许您可​​以直接重用列表,而无需转换为字符串。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM