Rename duplicate files in a zip file Java

别来无恙 提交于 2020-06-29 07:28:10

问题


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


回答1:


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.




回答2:


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

    });;



回答3:


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


来源:https://stackoverflow.com/questions/35286965/rename-duplicate-files-in-a-zip-file-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!