我想先排列文件,然后根据文件名中的数字指定的顺序重命名。
例如:
我有一个包含一堆不同文件的文件夹。 文件名由末尾的数字表示。 假设我们在该文件夹中有以下文件:
file_1.xml // Remains unchanged file_2.xml // Remains unchanged file_4.xml // Should be renamed to "file_3.xml" file_9.xml // Should be renamed to "file_4.xml" file_12.xml // Should be renamed to "file_5.xml"我怎么做? 我想创建一个可靠的干净方法,按顺序重命名文件。
至今:
private void updateFilesName() { for (int i = 1; i <= filesAmount; i++) { File file1 = new File(getFilesDir().getParent() + "/file_" + i + ".xml"); File file2 = new File(getFilesDir().getParent() + "/file_" + String.valueOf(i + 1) + ".xml"); if (!file1.exists() && file2.exists()) { file2.renameTo(file1); } } }但这只适用于2个文件位置之间的差异为1.(如file_2和file_4之间)此方法不适用于file_9和file_12 。
I want to arrange files first and rename them according to their order that is specified by a number in the file name.
For example:
I have a folder that contains a bunch of different files. The file names are indicated by a number at the end of it. Let's say we have the following files in that folder:
file_1.xml // Remains unchanged file_2.xml // Remains unchanged file_4.xml // Should be renamed to "file_3.xml" file_9.xml // Should be renamed to "file_4.xml" file_12.xml // Should be renamed to "file_5.xml"How do I do that? I want to create a reliable clean method that renames files in order.
So far:
private void updateFilesName() { for (int i = 1; i <= filesAmount; i++) { File file1 = new File(getFilesDir().getParent() + "/file_" + i + ".xml"); File file2 = new File(getFilesDir().getParent() + "/file_" + String.valueOf(i + 1) + ".xml"); if (!file1.exists() && file2.exists()) { file2.renameTo(file1); } } }But that only works if the difference between 2 file positions was 1. (like between file_2 and file_4) This method won't work for file_9 and file_12.
最满意答案
private void updateFilesName() { int j; for (int i = 1; i <= filesAmount; i++) { File file1 = new File(getFilesDir().getParent() + "/file_" + i + ".xml"); if (!file1.exists()) { j = i+1; while (!(new File(getFilesDir().getParent() + "/file_" + j + ".xml")).exists()) { j++; } (new File(getFilesDir().getParent() + "/file_" + j + ".xml")).renameTo(file1); } } } private void updateFilesName() { int j; for (int i = 1; i <= filesAmount; i++) { File file1 = new File(getFilesDir().getParent() + "/file_" + i + ".xml"); if (!file1.exists()) { j = i+1; while (!(new File(getFilesDir().getParent() + "/file_" + j + ".xml")).exists()) { j++; } (new File(getFilesDir().getParent() + "/file_" + j + ".xml")).renameTo(file1); } } }更多推荐
发布评论