【问题标题】:Rename duplicate files in a zip file Java重命名 zip 文件 Java 中的重复文件
【发布时间】:2016-05-19 03:18:49
【问题描述】:

我有几个文件,包括我必须压缩到存档中的重复文件。你知道一些工具能够在创建存档之前重命名重复文件 ex(cat.txt、cat(1).txt、cat(2)。 txt ...)?

【问题讨论】:

  • 你确定这是一个 Java 问题吗?
  • 为什么不呢?他添加了Java标签,因此他想用Java制作,因此我们给他一个Java代码。

标签: java string file rename archive


【解决方案1】:

在某个类中添加具有一些初始值的静态字段。

static int number = 1;

然后在您的 java 代码中,您可以使用 java 8 流和 Files 类以这种方式重命名重复项:

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

    });;

【讨论】:

    【解决方案2】:

    我创建了以下代码,可以轻松删除重复项:

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

    使用也很简单:

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

    结果是:

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

    请记住,重复项的数量应小于或等于给定字符串数组中的替代名称。您可以通过 while 循环修改来防止它:

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

    在这种情况下,其余文件将保持未命名。

    【讨论】:

    • 谢谢,但我想的是有一些图书馆为我做这件事。
    • 我不知道。无论如何,使用最多 10 行的一小段代码也应该没问题。
    【解决方案3】:

    试试这样的方法:

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

    【讨论】:

      猜你喜欢
      • 2021-06-23
      • 2013-03-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-03-15
      • 2014-08-03
      • 2023-04-09
      相关资源
      最近更新 更多