gpt4 book ai didi

java - 使用java用另一个列表的文件名重命名文件名列表

转载 作者:行者123 更新时间:2023-12-01 19:45:23 25 4
gpt4 key购买 nike

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 名称以及国家/地区名称。

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

最佳答案

我不会使用两个数组,而是使用单个 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());
}
}

关于java - 使用java用另一个列表的文件名重命名文件名列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53563845/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com