3

I want to rename my png file. Image current path like this:

/storage/emulated/0/Android/data/sample.png

I want to save this image under app's file directory. I give write external storage permission on runtime.

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 returns false. But I couldn't understand the reason.

zakjma
  • 2,030
  • 12
  • 40
  • 81

2 Answers2

0

Internal and external memory is two different file systems. Therefore renameTo() fails.

You will have to copy the file and delete the original

Original answer

zakjma
  • 2,030
  • 12
  • 40
  • 81
0

You can try the following method:

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);
        }
    }
}
Ahamadullah Saikat
  • 4,437
  • 42
  • 39