文件重命名失败返回false。

4
我希望您能够将我的png文件重命名。当前的图片路径如下所示:
/storage/emulated/0/Android/data/sample.png

我想把这张图片保存到应用程序的文件目录下。我在运行时授予了写入外部存储的权限。
File toFileDir = new File(getFilesDir() + "images");
if(toFileDir.exists()) {
    File file = new File("/storage/emulated/0/Android/data/sample.png");
    File toFile = new File(getFilesDir() + "images/sample-1.png");
    file.renameTo(toFile);
}

renameTo返回false。但我无法理解原因。


这段程序相关的内容翻译成中文:这两个文件在同一设备上吗?如果不是,renameTo 将无法工作。 - pskink
是的,同一设备。 - zakjma
Log.d the values of file and toFile - pskink
@pskink /storage/emulated/0/Android/data/sample.png。toFile /data/user/0/com.example.user.packageName/files/sample-1.png - zakjma
那么你怎么知道它们是相同的物理设备? - pskink
3个回答

0

内部和外部存储是两个不同的文件系统。因此,renameTo() 失败。

您将需要复制该文件并删除原始文件。

原始答案


0
在我的情况下,我得到了false,因为我附加了调试器,关闭它解决了这个问题。

0
你可以尝试以下方法:
private void moveFile(File src, File targetDirectory) throws IOException {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        if (!src.renameTo(new File(targetDirectory, src.getName()))) {
            // If rename fails we must do a true deep copy instead.
            Path sourcePath = src.toPath();
            Path targetDirPath = targetDirectory.toPath();
            try {
                Files.move(sourcePath, targetDirPath.resolve(sourcePath.getFileName()), StandardCopyOption.REPLACE_EXISTING);
            } catch (IOException ex) {
                throw new IOException("Failed to move " + src + " to " + targetDirectory + " - " + ex.getMessage());
            }
        }
    } else {
        if (src.exists()) {
            boolean renamed = src.renameTo(targetDirectory);
            Log.d("TAG", "renamed: " + renamed);
        }
    }
}

问题说明该权限已经在清单文件中。 - Jon

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接