统计文件夹中不同类型文件的出现次数,代码实现如下。
public class Demo {
private static Map<String,Integer> typeOccurrence = new LinkedHashMap<>();
private static List<File> otherFiles = new ArrayList<>();
public static void main(String[] args) {
System.out.println("请输入文件路径:");
fileClassificationStatistics(new File(new Scanner(System.in).nextLine()));
System.out.println(typeOccurrence);
System.out.println(otherFiles);
}
public static void fileClassificationStatistics(File file){
for (File listFile : file.listFiles()) {
if(listFile.isFile()){
String expandedName = listFile.getName().substring(listFile.getName().lastIndexOf(".") + 1);
if (typeOccurrence.containsKey(expandedName)){
typeOccurrence.put(expandedName,typeOccurrence.get(expandedName)+1);
}else{
typeOccurrence.put(expandedName,1);
}
} else if (listFile.isDirectory()){
fileClassificationStatistics(listFile);
} else {
otherFiles.add(listFile);
}
}
}
}