且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在 Android 中将文件从内部存储复制到外部存储

更新时间:2023-11-22 21:23:28

我解决了我的问题.问题出在目标路径中,在原始代码中:

I solved my issue. The problem was in the destination path, in the original code:

File dst = new File(dstPath);

变量dstPath 有完整的目标路径,包括文件名,这是错误的.这是正确的代码片段:

the variable dstPath had the full destination path, including the name of the file, which is wrong. Here is the correct code fragment:

String dstPath = Environment.getExternalStorageDirectory() + File.separator + "myApp" + File.separator;
File dst = new File(dstPath);

exportFile(pictureFile, dst);

private File exportFile(File src, File dst) throws IOException {

    //if folder does not exist
    if (!dst.exists()) {
        if (!dst.mkdir()) {
            return null;
        }
    }

    String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
    File expFile = new File(dst.getPath() + File.separator + "IMG_" + timeStamp + ".jpg");
    FileChannel inChannel = null;
    FileChannel outChannel = null;

    try {
        inChannel = new FileInputStream(src).getChannel();
        outChannel = new FileOutputStream(expFile).getChannel();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }

    try {
        inChannel.transferTo(0, inChannel.size(), outChannel);
    } finally {
        if (inChannel != null)
            inChannel.close();
        if (outChannel != null)
            outChannel.close();
    }

    return expFile;
}

感谢您的提示.