Android下载文件Out of Memory

时间:2016-09-13 15:53:47

标签: android file byte

我试图从互联网上下载文件。它运行良好,但如果文件大于2MB我得到此错误。谢谢你的帮助

    09-13 17:49:05.228 17994-18110/? E/dalvikvm-heap: Out of memory on a 286-byte allocation.
09-13 17:49:06.322 17994-18111/? E/dalvikvm-heap: Out of memory on a 16-byte allocation.
09-13 17:49:07.361 17994-17994/? E/dalvikvm-heap: Out of memory on a 72-byte allocation.
09-13 17:49:08.408 17994-18003/? E/dalvikvm-heap: Out of memory on a 24-byte allocation.
09-13 17:49:09.447 17994-18003/? E/dalvikvm-heap: Out of memory on a 28-byte allocation.
09-13 17:49:09.994 17994-18111/? E/dalvikvm-heap: Out of memory on a 28-byte allocation.
09-13 17:49:10.541 17994-17994/? E/dalvikvm-heap: Out of memory on a 28-byte allocation.

 public static byte[] is2Bytes(InputStream is) {
    byte[] buf = null;
    BufferedInputStream bufIS = null;
    if (is != null)
        try {
        ByteArrayOutputStream byteBuffer = new ByteArrayOutputStream();
        bufIS = new BufferedInputStream(is);
        buf = new byte[4096];
        int cnt;
        while ((cnt = bufIS.read(buf)) >= 0) {
            byteBuffer.write(buf, 0, cnt);
        }
        buf = byteBuffer.size() > 0 ? byteBuffer.toByteArray() : null;
    } catch (Exception ignore) {
    } finally {
        try {
            if (bufIS != null) bufIS.close();
        } catch (Exception ignore) {
        }
    }
    return buf;
}

1 个答案:

答案 0 :(得分:2)

您正在尝试将整个文件下载到内存中。这对大文件不起作用,因为你不会有大量连续RAM的堆空间。

将文件写入磁盘,或者以块的形式使用内存(例如,下载4K,使用4K,丢弃4K,重复)。