L. Tudy
L. Tudy

Reputation: 37

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 ...)?

Upvotes: 1

Views: 2196

Answers (3)

JammuPapa
JammuPapa

Reputation: 148

Try an approach like this one:

File folder = new File("your/path");
HashMap<String,Integer> fileMap = new HashMap<String,Integer>();
File[] listOfFiles = folder.listFiles();
for (int i = 0; i < listOfFiles.length; i++) {
    if(fileMap.containsKey(listOfFiles[i])){
             String newName = listOfFiles[i]+"_"
                +fileMap.get(listOfFiles[i]);
             fileMap.put(listOfFiles[i],fileMap.get(listOfFiles[i])+1);
             listOfFiles[i].renameTo(newName);
             fileMap.put(newName,1); // can be ommitted
    }else{
            fileMap.put(listOfFiles[i],1);
    }
}

Upvotes: 0

Nikolas
Nikolas

Reputation: 44486

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.

Upvotes: 1

Nikolay Tomitov
Nikolay Tomitov

Reputation: 947

Add static field in some class with some initial value.

static int number = 1;

Then in your java code you may rename duplicates in this way using java 8 streams and Files class :

Set<String> files = new HashSet<String>();

    youCollectionOfFiles.stream().forEach((file)->{
        if (files.add(file.getFileName().toString()) == false) {
            try {
                //rename the file
                Files.move(file, 
                        file.resolveSibling(file.getFileName().toString() + (number++)));
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

    });;

Upvotes: 0

Related Questions