0

我想保存一个非常大的在线 xml 文件(大约 33mb)。我正在尝试在 StringBuilder 中获取 xml 文件,将其转换为字符串,然后通过 FileOutputStream 将文件保存在内部存储/Sdcard 中。

但我内存不足,应用程序崩溃。当我尝试从 StringBuilder 获取字符串中的值时发生崩溃。

这是我当前的代码:

        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpPost httpPost = new HttpPost("sorry cant paste the actual link due copyrights.xml");

        HttpResponse httpResponse = httpClient.execute(httpPost);
        HttpEntity httpEntity = httpResponse.getEntity();
        is = httpEntity.getContent();            

    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    try {
        BufferedReader reader = new BufferedReader(new InputStreamReader(
                is, "iso-8859-1"), 8);
        StringBuilder sb = new StringBuilder();
        String line = null;
        while ((line = reader.readLine()) != null) {

            sb.append(line + "\n");
        }
        is.close();

        String result = sb.toString();

        System.out.println(result);

        FileOutputStream fos = openFileOutput("test.xml", Context.MODE_PRIVATE);

        fos.write(sb.toString().getBytes());

        fos.close();

    } catch (Exception e) {
        Log.e("Buffer Error", "Error converting result " + e.toString());
    }
4

2 回答 2

2

您的解决方案的问题是它需要大量的应用程序内存,因为 xml 字符串完全加载到内存中。

您可以通过像这样处理小 1kb 块中的数据来避免这种情况:

    is = httpEntity.getContent();

    FileOutputStream fos = openFileOutput("test.xml", Context.MODE_PRIVATE);

    byte[] buffer = new byte[1024];
    int length;
    while ((length = is.read(buffer))>0){
        fos.write(buffer, 0, length);
    }

    fos.flush();
    fos.close();
    is.close();
于 2012-04-23T09:31:51.267 回答
1

你可以试试下面的代码吗?

BufferedReader reader = new BufferedReader(new InputStreamReader(
        is, "iso-8859-1"), 8);
FileOutputStream fos = openFileOutput("test.xml", Context.MODE_PRIVATE);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {

    sb.append(line + "\n");

    if (sb.toString().length() > 10000) {
       fos.write(sb.toString().getBytes());
       fos.flush();
       sb = new StringBuilder();
    }
}
is.close();

fos.close();
于 2012-04-23T09:10:23.780 回答