Search code examples
javaandroidalgorithmfilefile-rename

How to arrange and rename files according to number?


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.


Solution

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