【问题标题】:Copy file (image) from CacheDir to SD Card将文件(图像)从 CacheDir 复制到 SD 卡
【发布时间】:2011-05-17 11:03:13
【问题描述】:

我希望能够从 android 设备的内部缓存中移动或复制文件,并将其放入 SD 卡上的永久存储中。这是我目前所拥有的:

public void onClickSaveSecret(View v){

    File image = new File(getApplication().getCacheDir() + "/image.png");
    File newImage = new File(Environment.getExternalStorageDirectory() + "/image.png");

    Toast.makeText(this, "Image Saved", 100).show();

}

【问题讨论】:

  • 那么你的问题是什么?您不知道如何复制内容?

标签: java android file copy


【解决方案1】:
/**
 * copy file from source to destination
 *
 * @param src source
 * @param dst destination
 * @throws java.io.IOException in case of any problems
 */
void copyFile(File src, File dst) throws IOException {
    FileChannel inChannel = new FileInputStream(src).getChannel();
    FileChannel outChannel = new FileOutputStream(dst).getChannel();
    try {
        inChannel.transferTo(0, inChannel.size(), outChannel);
    } finally {
        if (inChannel != null)
            inChannel.close();
        if (outChannel != null)
            outChannel.close();
    }
}

【讨论】:

    【解决方案2】:

    试试这个方法

    /**
    * @param sourceLocation like this /mnt/sdcard/XXXX/XXXXX/15838e85-066d-4738-a243-76c461cd8b01.jpg
    * @param destLocation /mnt/sdcard/XXXX/XXXXX/15838e85-066d-4738-a243-76c461cd8b01.jpg
    * @return true if successful copy file and false othrerwise
    *  
    * set this permissions in your application WRITE_EXTERNAL_STORAGE ,READ_EXTERNAL_STORAGE 
    *  
    */
    public static boolean copyFile(String sourceLocation, String destLocation) {
        try {
            File sd = Environment.getExternalStorageDirectory();
            if(sd.canWrite()){
                File source=new File(sourceLocation);
                File dest=new File(destLocation);
                if(!dest.exists()){
                    dest.createNewFile();
                }
                if(source.exists()){
                    InputStream  src=new FileInputStream(source);
                    OutputStream dst=new FileOutputStream(dest);
                     // Copy the bits from instream to outstream
                    byte[] buf = new byte[1024];
                    int len;
                    while ((len = src.read(buf)) > 0) {
                        dst.write(buf, 0, len);
                    }
                    src.close();
                    dst.close();
                }
            }
            return true;
        } catch (Exception ex) {
            ex.printStackTrace();
            return false;
        }
    }
    

    更多信息请访问AndroidGuide

    【讨论】:

    • 1.如果您可以对问题发布相同的答案,则表明问题是重复的,因此您应该标记而不是回答。 2. 请不要在您的回答中宣传您的博客。
    猜你喜欢
    • 2011-06-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-08
    • 1970-01-01
    • 2014-02-10
    • 1970-01-01
    相关资源
    最近更新 更多