【问题标题】:OutOfMemoryError while converting Stream to String in Android在Android中将Stream转换为String时出现OutOfMemoryError
【发布时间】:2012-11-21 18:05:43
【问题描述】:

我正在从 Assets 文件夹加载 xml 文件。我得到 OutOfMemoryError。 我使用的代码是

private String convertStreamToString(InputStream is) {  
    BufferedReader reader = new BufferedReader(new InputStreamReader(is));
    StringBuilder sb = new StringBuilder();

    String line = null;
    try {
        while ((line = reader.readLine()) != null) {
            sb.append(line + NEW_LINE);
        }
        reader.close();

    } catch (IOException e) {
        //do nothing.
    } finally {
        try {
            reader.close();
        } catch (IOException e) {
            //do nothing.    
        }
    }
    reader=null;
    return sb.toString();
}

是否有其他方法可以摆脱此异常。 如果您发布任何代码,它将更有帮助。 提前致谢。

【问题讨论】:

  • 您可以从 XML 文件中读取一行,对其进行处理,然后继续下一行。不要将整个文件读入内存,文件可能很大。

标签: java android out-of-memory bufferedreader


【解决方案1】:

下面试试

您是否尝试过将流转换为字符串的内置方法?它是 Apache Commons 库 (org.apache.commons.io.IOUtils) 的一部分。

那么你的代码就是这一行:

字符串总数 = IOUtils.toString(inputStream);

它的文档可以在这里找到:http://commons.apache.org/io/api-1.4/org/apache/commons/io/IOUtils.html#toString%28java.io.InputStream%29

Apache Commons IO 库可以从这里下载:http://commons.apache.org/io/download_io.cgi

【讨论】:

  • 你能指导我如何使用这个吗?我有点困惑。
  • 你必须添加外部库
【解决方案2】:

把线=空;在附加到某人之后的while循环中。

【讨论】:

  • 很抱歉将此作为答案,因为我无法在其他人的帖子中发表评论。
【解决方案3】:

使用字符串解析大型 Xml 不是一个好主意。您应该转向解析器的流式传输版本。 Google Http Java Client 提出了这样一个库:http://code.google.com/p/google-http-java-client

【讨论】:

    猜你喜欢
    • 2023-03-31
    • 2021-07-22
    • 2018-08-25
    • 2020-09-15
    • 1970-01-01
    • 1970-01-01
    • 2021-08-28
    • 2014-07-20
    • 2015-07-31
    相关资源
    最近更新 更多