读取一个12MB的文件出现问题 (java.lang.OutOfMemoryError)

3
我需要打开一个大小为12兆字节的文件,但实际上我正在创建一个12834566字节的缓冲区,因为我正在为Android移动系统开发此应用程序。
然后,我应该使用1024 K字节的块而不是一个12 M字节的块进行阅读,并使用for循环进行操作,但我不知道如何做到这一点,我需要一点帮助。
以下是我的代码:
File f = new File(getCacheDir()+"/berlin.mp3");
        if (!f.exists()) try {
          InputStream is = getAssets().open("berlin.mp3");
          int size = is.available();
          byte[] buffer = new byte[size];
          is.read(buffer);
          is.close();
          FileOutputStream fos = new FileOutputStream(f);
          fos.write(buffer);
          fos.close();
        } catch (Exception e) { throw new RuntimeException(e); }

请问,有人能告诉我需要更改哪些代码才能够每次读取1024 K字节的块而不是12 M字节的块吗?

谢谢!


你不能逐步创建 byte[]。当你读取数据时,你必须将数据馈送到数据去向的位置。 - Peter Lawrey
@AndroidUser99 很好的问题,给你点赞,先生。 - Nikhil Agrawal
3个回答

4
尝试每次复制1千字节。
File f = new File(getCacheDir()+"/berlin.mp3");
if (!f.exists()) try {
     byte[] buffer = new byte[1024];
     InputStream is = getAssets().open("berlin.mp3");
     FileOutputStream fos = new FileOutputStream(f);
     int len;
     while((len = is.read(buffer)) > 0) 
        fos.write(buffer, 0, len);
} catch (Exception e) { 
     throw new RuntimeException(e); 
} finally {
     IOUtils.close(is); // utility to close the stream properly.
     IOUtils.close(fos);
}

Android支持类似于UNIX的符号链接或硬链接吗?如果支持的话,这将更快/更有效率。

您没有正确关闭流。 - Marek Potociar
@peter Larey 大师,您的回答太棒了。解决了我的问题。+1 给您。 - Nikhil Agrawal

1
File f = new File(getCacheDir()+"/berlin.mp3");
InputStream is = null;
FileOutputStream fos = null;
if (!f.exists()) try {
    is = getAssets().open("berlin.mp3");
    fos = new FileOutputStream(f);
    byte[] buffer = new byte[1024];
    while (is.read(buffer) > 0) {
        fos.write(buffer);
    }
} catch (Exception e) { 
    throw new RuntimeException(e); 
} finally { 
    // proper stream closing
    if (is != null) {
        try { is.close(); } catch (Exception ignored) {} finally {
           if (fos != null) {
               try { fos.close(); } catch (Exception ignored2) {}
           }
        }
    }
}

0
        import org.apache.commons.fileupload.util.Streams;

        InputStream in = getAssets().open("berlin.mp3");
        OutputStream out = new FileOutputStream(f);
        Streams.copy(in, out, true);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接