Search code examples
javastringfilerenamearchive

Rename duplicate files in a zip file Java


I have several files including duplicates which I have to compress into an archive.Do you know some tool able to rename duplicate files before creating the archive ex(cat.txt, cat(1).txt, cat(2).txt ...)?


Solution

  • I have created the following code that easily removes duplicates:

    static void renameDuplicates(String fileName, String[] newName) {
        int i=1;
        File file = new File(fileName + "(1).txt");
        while (file.exists() && !file.isDirectory()) {
            file.renameTo(new File(newName[i-1] + ".txt"));
            i++;
            file = new File(fileName + "(" + i + ").txt");
        }
    }
    

    Use is simply as well:

    String[] newName = {"Meow", "MeowAgain", "OneMoreMeow", "Meowwww"};
    renameDuplocates("cat", newName);
    

    The result is:

    cat.txt     ->    cat.txt
    cat(1).txt  ->    Meow.txt
    cat(2).txt   ->   MeowAgain.txt
    cat(3).txt   ->   OneMoreMeow.txt
    

    Keep on mind that the number of duplicates should be smaller or equal than alternative names in the array of string given. You can prevent it with while cycle modification to:

    while (file.exists() && !file.isDirectory() && i<=newName.length)
    

    In this case the remaining files will keep unnamed.