[英]Problems reading a huge file of 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);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.