【问题标题】:File.renameTo return falseFile.rename 要返回 false
【发布时间】:2018-04-16 07:36:34
【问题描述】:

我想重命名我的 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 将不起作用
  • 是的,相同的设备。
  • Log.d filetoFile 的值
  • @pskink /storage/emulated/0/Android/data/sample.png。 toFile /data/user/0/com.example.user.packageName/files/sample-1.png
  • 那么你怎么知道它们是相同的物理设备?

标签: android file file-rename


【解决方案1】:

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

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

Original answer

【讨论】:

    【解决方案2】:

    您可以尝试以下方法:

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

    【讨论】:

    • 问题表明此权限已在清单中。
    猜你喜欢
    • 2011-03-02
    • 2012-02-22
    • 2011-06-02
    • 1970-01-01
    • 1970-01-01
    • 2011-06-15
    • 2019-06-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多