我正在尝试使用以下代码将原始资源(它是一个zip文件)从应用程序移动到SD卡:
void copyFile() throws IOException {
File dest = Environment.getExternalStorageDirectory();
InputStream in = context.getResources().openRawResource(R.raw.file);
OutputStream out = new FileOutputStream(dest + "/file.zip");
// Transfer bytes from in to out
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
in.close();
out.close();
}
然而,当我检查SD卡上的文件时,我收到消息: “存档格式未知或已损坏”
为什么文件没有正确复制?
答案 0 :(得分:2)
我对你的代码做了一些修改:
File dest = Environment.getExternalStorageDirectory();
InputStream in = context.getResources().openRawResource(R.raw.file);
// Used the File-constructor
OutputStream out = new FileOutputStream(new File(dest, "file.zip"));
// Transfer bytes from in to out
byte[] buf = new byte[1024];
int len;
try {
// A little more explicit
while ( (len = in.read(buf, 0, buf.length)) != -1){
out.write(buf, 0, len);
}
} finally {
// Ensure the Streams are closed:
in.close();
out.close();
}
这个适用于我(不是在Android上,而是在普通计算机上)。我所做的修改:
File
-constructor作为FileOutputStream
。try-catch
- 块来确保Streams正在获取
即使在读/写时出现错误/异常,也会关闭。read
-method(基本上是
和你的一样)因为当我告诉他该怎么做时我会感觉更好。正如我上面所说,我在我的电脑上试过它并且有效。证明:
[luke@KeksDose Downloads]$ md5sum quick_action.zip
4e45fa08f24e971961dd60c3e81b292d quick_action.zip
[luke@KeksDose Downloads]$ md5sum quick_action_copy.zip
4e45fa08f24e971961dd60c3e81b292d quick_action_copy.zip