【问题标题】:Rename filenames list with another list's filenames with java用 java 用另一个列表的文件名重命名文件名列表
【发布时间】:2018-11-30 19:38:10
【问题描述】:
import java.io.*;

public class Main {

    public static void main(String[] args) {


        // change file names in 'Directory':
        String absolutePath = "/storage/emulated/0/Gadm";
        File dir = new File(absolutePath);
        File[] filesInDir = dir.listFiles();
        int i = 0;



        for(File file:filesInDir) {

            i++;



            String[] iso = {
                "AFG",
                "XAD",
                "ALA",
                "ZWE"};


            String[] country = {
                "Afghanistan",
                "Akrotiri and Dhekelia",
                "Åland",
                "Zimbabwe"};


        String name = file.getName();
        String newName = name.replace(iso[i],country[i]);



        String newPath = absolutePath + "/" + newName;
        file.renameTo(new File(newPath));

          System.out.println(name + " has been changed to " + newName);
        }


    }
}

我有一个名为 Gadm 的目录,它包含一个文件列表,名称如下,后跟国家/地区的 iso 代码,例如 iso.kmz 我将使用其对应的国家/地区名称重命名所有文件名,以成为 country.kmz

iso 名称以正确的顺序存储在数组中,还有国家名称。

我尝试了上面的代码,但它不起作用

【问题讨论】:

    标签: java arrays filenames


    【解决方案1】:

    我将使用单个 HashMap,而不是使用两个数组,其中键是国家 ISO 代码,值是相关的国家名称。喜欢:

    String absolutePath = "/storage/emulated/0/Gadm/";
    HashMap<String, String> countryCodes = new HashMap<>();
    countryCodes.put("AFG","Afghanistan");
    countryCodes.put("XAD","Akrotiri and Dhekelia");
    countryCodes.put("ALA","Åland");
    countryCodes.put("ZWE","Zimbabwe");
    
    for(Map.Entry<String, String> entry : countryCodes.entrySet()) {
        File file = new File(absolutePath + entry.getKey());
        if (file.renameTo(new File(absolutePath + entry.getValue()))) {
            System.out.println("Successfully renamed " + entry.getKey() + " to " + entry.getValue());
        } else {
            System.out.println("Failed to rename " + entry.getKey() + " to " + entry.getValue() +
                    ". Please make sure filepath exists: " + absolutePath + entry.getKey());
        }
    }
    

    【讨论】:

    • 很好,我可能会放弃我正在写的答案——但为什么要循环通过entrySet?您可能有实际不存在的文件的 countryCode 条目。相反,循环浏览文件,拆分扩展名,然后countryName = countryCodes.get(extension),这样您就只循环浏览实际找到的文件。
    • @StephenP 真的。您要么正在处理可能缺少 HashMap 键的文件,要么正在处理缺少文件的 HashMap 键。无论哪种情况,您都应该相应地处理错误。我将添加一个条件来处理 renameTo 返回的布尔值。
    【解决方案2】:

    作为替代方案,您可以使用Path 而不是File

    public static void rename(Path source) throws IOException {
        Map<String, String> countries = countries.get();
    
        Files.list(source)
             .filter(path -> Files.isRegularFile(path))
             .filter(path -> countries.containsKey(getFileName.apply(path)))
             .forEach(path -> {
                 try {
                     Files.move(path, source.resolve(countries.get(getFileName.apply(path)) + getFileExt.apply(path)));
                 } catch(IOException e) {
                     e.printStackTrace();
                 }
             });
    }
    
    private static final Function<Path, String> getFileName = path -> {
        String fileName = path.getFileName().toString();
        return fileName.substring(0, fileName.lastIndexOf('.')).toUpperCase();
    };
    
    private static final Function<Path, String> getFileExt = path -> {
        String fileName = path.getFileName().toString();
        return fileName.substring(fileName.lastIndexOf('.'));
    };
    
    private static Supplier<Map<String, String>> countries = () -> {
        Map<String, String> map = new HashMap<>();
        map.put("AFG", "Afghanistan");
        map.put("XAD", "Akrotiri and Dhekelia");
        map.put("ALA", "Åland");
        map.put("ZWE", "Zimbabwe");
        return Collections.unmodifiableMap(map);
    };
    

    客户端代码为:rename(Paths.get("h:/gadm"))

    【讨论】:

      猜你喜欢
      • 2011-10-02
      • 1970-01-01
      • 2015-10-23
      • 1970-01-01
      • 2014-02-22
      • 2017-12-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多