读取12 MB的巨大文件时出现问题(java.lang.OutOfMemoryError)

我需要打开一个12兆字节的文件,但实际上我正在创建一个12834566字节的缓冲区,因为该文件的大小是12MB,我正在为Android移动系统开发这个应用程序。

然后,我想我必须用1024 KB的块读取而不是一块12 MB的块,有一个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 KB的块而不是一块12 MB的块吗?

谢谢!

尝试一次复制1 KB。

 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这样的符号或手动链接? 如果是这样,这将更快/更有效。

 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) {} } } } } 
  import org.apache.commons.fileupload.util.Streams; InputStream in = getAssets().open("berlin.mp3"); OutputStream out = new FileOutputStream(f); Streams.copy(in, out, true);