What can go wrong with file.renameTo(file) in Android
android, file, file-io, file-rename, java
Solution
In Android File.renameTo calls Linux rename() (via libcore). You can check POSIX standard for the list of possible failures, it may be slightly different on Linux, but should give you general idea.
Also note this statement:
If the rename() function fails for any reason other than [EIO], any file named by new shall be unaffected.
Problem
I'm reading the documentation of `renameTo(File)` in the `File.class` of the Android SDK doc. We've been using this method for a while in production, still I have been wondering what are the possible things that can go wrong. The documentation says Renames this file to newPath. This operation is supported for both files and directories. Many failures are possible. Some of the more likely failures include: Write permission is required on the directories containing both the source and destination paths. Search permission is required for all parents of both paths. Both paths be on the same mount point. On Android, applications are most likely to hit this restriction when attempting to copy between internal storage and an SD card. Note that this method does not throw IOException on failure. Callers must check the return value. What are other possible reasons why `renameTo()` might fail (referring to more likely failures)? Is there a guaranteed state after calling `renameTo`? When `renameTo()` fails, can I rely on having still my original file? Any other conditions I want to check to uber sure that it works beside the described ones from the docs?