我需要打开一个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的块吗?
谢谢!
答案 0 :(得分:4)
尝试一次复制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等符号或手动链接?如果是这样,这将更快/更有效。
答案 1 :(得分: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) {}
}
}
}
}
答案 2 :(得分:0)
import org.apache.commons.fileupload.util.Streams;
InputStream in = getAssets().open("berlin.mp3");
OutputStream out = new FileOutputStream(f);
Streams.copy(in, out, true);