将文件(图像)从 CacheDir 复制到 SD 卡

2022-01-20 00:00:00 复制 file android java

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

I want to be able to either move or copy a file from the internal Cache of an android device and put this into permanent storage on the SD Card. This is what I have so far:

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();

}

推荐答案

/**
 * 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();
    }
}

相关文章