File.rename返回 false

问题描述 投票:0回答:3

我想重命名我的 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。但我无法理解原因。

android file file-rename
3个回答
0
投票

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

您必须复制文件并删除原始文件

原答案


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

0
投票

就我而言,我得到了

false
,因为我附加了调试器,将其关闭解决了问题🤷🏻u200d♂️

© www.soinside.com 2019 - 2024. All rights reserved.