android - 下载文件时内存不足

标签 android download out-of-memory

HttpResponse responseGet;
        try {
            responseGet = client.execute(get);
            switch (responseGet.getStatusLine().getStatusCode()) {
            case 200:
                File SDCardRoot = Environment.getExternalStorageDirectory();
                File directory = new File(SDCardRoot
                        + "/OfflineDocuments/"
                        + (document.getPath() == null ? ""
                                : (document.getPath() + "/")));
                directory.mkdirs();
                File file = new File(directory, fileName);
                InputStream is = responseGet.getEntity().getContent();
                BufferedInputStream bis = new BufferedInputStream(is);

                ByteArrayBuffer baf = new ByteArrayBuffer(50);
                int current = 0;
                while ((current = bis.read()) != -1) {
                    baf.append((byte) current);
                }

                FileOutputStream fos = new FileOutputStream(file);
                fos.write(baf.toByteArray());
                fos.close();
                break;

            default:
                Log.e("Statuscode", "Unexpected status code: "
                        + responseGet.getStatusLine().getStatusCode());
                break;
            }

        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (Exception e1) {
            e1.printStackTrace();
        }

这适用于小型文档。但对于大于几 MB 的文档,此代码会因“OutOfMemoryException”而崩溃。有什么想法吗?

最佳答案

您正在将文件完整地写入内存,然后将该缓冲文件写入存储。相反,跳过缓冲并在 fragment 进入时将其写入存储。

FileOutputStream fos = new FileOutputStream(file);
while ((current = bis.read()) != -1) {
    fos.write(current);
}
fos.close();

注意...不是 Android 开发人员,所以不知道这是否真的有效,所以将其视为伪代码。

关于android - 下载文件时内存不足,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8730269/

相关文章:

c# - Crystal Reports ActiveX Viewer 在 VB6/.NET App Windows 7 中导致内存不足异常

c - 哪个更好, ch = '\n' ;写(1,&ch,1);或 putchar ('\n' );?

android - TrafficStats tx 和 rx 值何时重置?

android - retrofit api中的任意属性通过json反序列化获取

java - 单击按钮时选择方法

android - 为什么我的 Fragment 没有实例化? Activity 到 Fragments 的通信

javascript - 服务器重定向到下载文件后捕获重新加载/结束请求事件

android - Cordova FileTransfer 下载错误

C# 文件下载已损坏

c# - 在单元测试中出现 OutOfMemoryException