资源复制到SD卡给出的Andr​​oid损坏的文件 [英] copying resource to sdcard gives a damaged file in android

查看:108
本文介绍了资源复制到SD卡给出的Andr​​oid损坏的文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图用这个code从应用程序移动原料资源(这是一个zip文件),以SD卡:

I am trying to move a raw resource (it is a zip file) from the app to SD card using this code:

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卡上的文件,我得到的消息:
归档或者是未知格式或已损坏

However, when I check the file on the sd card I get the message: "The archive is either in an unknown format or damaged"

为什么文件没有正确复制?

Why is the file not being copied properly?

推荐答案

我在你的code做了一些小改动:

I made some little modifications on your code:

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,但一个正常的计算机上)。这些修改我在其中:

This one worked for me (not on Android but on a normal computer). The modifications I made where:


  • 我用<一个href=\"http://download.oracle.com/javase/6/docs/api/java/io/File.html#File%28java.io.File,%20java.lang.String%29\"相对=nofollow> 文件 -constructor 的<一个href=\"http://download.oracle.com/javase/1.4.2/docs/api/java/io/FileOutputStream.html#FileOutputStream%28java.io.File%29\"相对=nofollow> 的FileOutputStream

  • 我用了一个的try-catch - 块,以确保流越来越
    封闭的,即使是在读取/写入错误/异常。

  • 我用了更明确的<一个href=\"http://download.oracle.com/javase/6/docs/api/java/io/InputStream.html#read%28byte%5B%5D,%20int,%20int%29\"相对=nofollow> -method (这基本上是
    你的一样),因为我感觉好多了,当我告诉他该怎么做。

  • I used the File-constructor for the FileOutputStream.
  • I used a try-catch-block to ensure that the Streams are getting closed, even when there is an error/exception while reading/writing.
  • I used the more explicit read-method (which is basically the same as yours) because I feel better when I tell him what to do.

正如我前面所说,我试了一下我的电脑上,它的工作。证明:

As I said above, I tried it on my computer and it worked. Proof:

[luke@KeksDose Downloads]$ md5sum quick_action.zip 
4e45fa08f24e971961dd60c3e81b292d  quick_action.zip
[luke@KeksDose Downloads]$ md5sum quick_action_copy.zip 
4e45fa08f24e971961dd60c3e81b292d  quick_action_copy.zip

这篇关于资源复制到SD卡给出的Andr​​oid损坏的文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆