In my application, I need to record video. Before start of recording in I\'m assigning a name and directory to it. After recording is finished user has ability to rename his
This is what I ended up using. It handles the case where there is an existing file with the same name by adding an integer to the file name.
@NonNull
private static File renameFile(@NonNull File from,
@NonNull String toPrefix,
@NonNull String toSuffix) {
File directory = from.getParentFile();
if (!directory.exists()) {
if (directory.mkdir()) {
Log.v(LOG_TAG, "Created directory " + directory.getAbsolutePath());
}
}
File newFile = new File(directory, toPrefix + toSuffix);
for (int i = 1; newFile.exists() && i < Integer.MAX_VALUE; i++) {
newFile = new File(directory, toPrefix + '(' + i + ')' + toSuffix);
}
if (!from.renameTo(newFile)) {
Log.w(LOG_TAG, "Couldn't rename file to " + newFile.getAbsolutePath());
return from;
}
return newFile;
}