【问题标题】:Android - Save Large Xml File (Internal / sdcard)Android - 保存大型 Xml 文件(内部/sdcard)
【发布时间】:2012-04-23 09:04:02
【问题描述】:

我想保存一个非常大的在线 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());
    }

【问题讨论】:

    标签: android xml parsing sd-card out-of-memory


    【解决方案1】:

    您的解决方案的问题是它需要大量的应用程序内存,因为 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();
    

    【讨论】:

    • 试试这个,你会知道结果的。
    【解决方案2】:

    你能试试下面的代码吗?

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

    【讨论】:

    • 我一定会试试这个,会尽快通知你。
    • 这工作得很好,但@k3b 方法似乎比这更好。感谢您的回答。
    猜你喜欢
    • 1970-01-01
    • 2014-12-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-25
    • 1970-01-01
    • 2023-03-10
    相关资源
    最近更新 更多