OutOfMemoryException异常引起的大串 [英] OutOfMemoryException caused by large Strings

查看:189
本文介绍了OutOfMemoryException异常引起的大串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

即时通讯使用使用下面的方法来从的WebAPI捕捞数据:

Im using using following Method to catch Data from a webapi:

public static String sendRequest(String requestURL, String data)
        throws IOException {
    URL url = new URL(requestURL + "?" + data);
    URLConnection conn = url.openConnection();
    conn.setReadTimeout(10000);
    BufferedReader in = new BufferedReader(new InputStreamReader(
            conn.getInputStream()));

    String inputLine;
    StringBuilder answerBuilder = new StringBuilder("");
    try {
        while ((inputLine = in.readLine()) != null)
            answerBuilder.append(inputLine);
        in.close();
    } catch (Exception e) {
    }

    return answerBuilder.toString();
}

使用一些请求,这导致引起的过小HEAPSIZE一个的OutOfMemoryError:

With some requests, this leads to a OutOfMemoryError caused by a too small HeapSize:

(...)Caused by: java.lang.OutOfMemoryError: (Heap Size=17927KB, Allocated=14191KB, Bitmap Size=2589KB)
at java.lang.AbstractStringBuilder.enlargeBuffer(AbstractStringBuilder.java:95)
at java.lang.AbstractStringBuilder.append0(AbstractStringBuilder.java:132)
at java.lang.StringBuilder.append(StringBuilder.java:272)
at java.io.BufferedReader.readLine(BufferedReader.java:423)
at com.elophant.utils.HTTPUtils.sendRequest(HTTPUtils.java:23)
at (..)

我已经从普通的字符串操作交换像字符串的答案+ = inputLine 来一个StringBuilder,但这没有帮助。我该如何解决这个问题呢?通过出口JVM_ARGS =增加最大堆大小 - Xmx1024m -XX:MaxPermSize =256米心不是一种选择,因为它的Andr​​oid应用程序

I already swapped from normal String operations like String answer += inputLine to a StringBuilder but this didnt help. How can i solve this Problem? Increasing maximum heap size via export JVM_ARGS="-Xmx1024m -XX:MaxPermSize=256m" isnt an option as its an android app.

推荐答案

一个解决办法是坚持内容下载到的存储

One solution would be to persist the content being downloaded to a storage.

根据你是什么下载,你可以在它的读取,并将其存储在一个的 SQL精简版数据库。这将允许您使用查询语言事后处理数据。这将是非常有用的,如果下载的文件是一个JSON或XML。

Depending on what you are download you could parse it during its read and store it in a SQL Lite DataBase. This would allow you to use Query language to handle data afterwards. This would be really useful if file being downloaded is a JSON or XML.

在JSON,你可以得到的的InputStream ,你已经做的和读取数据流的的 JSON阅读器。对于从JSON每一条记录读取,你可以在一个表中存储(或多个表的具体取决于每个记录结构)。从这种方法的好处是,在最后你不需要的文件处理,你已经有你的数据库可供查询范围内分布在表中的数据。

In JSON you could get the InputStream as you already do and read stream with the JSON Reader. For every record read from the JSON you can store in a table (or more tables depending on how each record is structured). The good thing from this approach is that at the end you don't need file handling and you already have your data distributed in tables within your database ready to be queried.

这篇关于OutOfMemoryException异常引起的大串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆