如何以编程方式将文件从内部存储器移动到 android 中的 sdcard?

How to programmatically move files from internal memory to sdcard in android?

如何在android中将文件从设备的内部存储器移动到外部存储器?请提供代码示例。我的代码如下

    private void moveFile(File file, File dir) throws IOException {
    File newFile = new File(dir, file.getName());
    FileChannel outputChannel = null;
    FileChannel inputChannel = null;
    try {
        outputChannel = new FileOutputStream(newFile).getChannel();
        inputChannel = new FileInputStream(file).getChannel();
        inputChannel.transferTo(0, inputChannel.size(), outputChannel);
        inputChannel.close();
        file.delete();
    } finally {
        if (inputChannel != null) inputChannel.close();
        if (outputChannel != null) outputChannel.close();
    }

}

从您的路径中删除结尾的斜杠。不需要,因为 example.png 不是目录。实际上不要对 SD 卡的路径进行硬编码,因为它可能因设备而异。尝试 Environment.getExternalStorageDirectory() 获取 sdcard 的路径,然后在最后添加任何尾随路径。

请看一下documentation