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
。 }}
存储在数组中的iso名称以及国家/地区名称和正确的顺序。
我在上面尝试了此代码,但没有用
答案 0 :(得分:2)
我将使用单个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());
}
}
答案 1 :(得分:1)
作为替代方案,您可以使用Path
的{{1}} istead:
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); };