android, How to rename a file?

前端 未结 9 2127
Happy的楠姐
Happy的楠姐 2020-11-28 09:58

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

9条回答
  •  无人及你
    2020-11-28 10:17

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

提交回复
热议问题