java获取某个文件夹下每种文件的个数

叁歲伎倆 2024-04-22 05:15 94阅读 0赞

需求:

  1. /*
  2. * 需求:统计一个文件夹中每种文件的个数并打印。(考虑子文件)
  3. * 打印格式如下:
  4. * txt:3个
  5. * doc:4个
  6. * jpg:6个
  7. * */
  8. 需要统计某个文件夹下的文件个数,这里以D盘为例,需要注意的是,在C盘中某些文件或文件夹是需要管理员权限才可以访问的。
  9. 需要用到java中的FIle类以及HashMap集合的内容
  10. package a02dome2.file;
  11. import java.io.File;
  12. import java.util.HashMap;
  13. import java.util.Map;
  14. import java.util.Set;
  15. public class fileCount {
  16. public static void main(String[] args) {
  17. /*
  18. * 需求:统计一个文件夹中每种文件的个数并打印。(考虑子文件)
  19. * 打印格式如下:
  20. * txt:3个
  21. * doc:4个
  22. * jpg:6个
  23. * */
  24. //定义文件路径
  25. File file = new File("D:\\5e\\5EClient");
  26. //将文件类型和个数返回一个HasMap对象
  27. HashMap<String, Integer> count = getCount(file);
  28. //lambda表达式对HashMap集合进行遍历,得到需要统计文件的个数
  29. count.forEach((k,v)->{
  30. System.out.println(k+":"+v+"个");
  31. });
  32. }
  33. //定义方法对文件进行统计,返回一个HashMap对象
  34. public static HashMap<String,Integer> getCount(File file){
  35. HashMap<String,Integer> map = new HashMap<>();
  36. //将文件用文件数组进行存储,方便对文件或文件夹进行遍历和判断
  37. File[] files = file.listFiles();
  38. if(files != null){
  39. for (File file1 : files) {
  40. if(file1.isFile()){
  41. //当前file1是文件
  42. //获取文件名
  43. String name = file1.getName();
  44. //将文件名用.进行切割并返回String数组
  45. String[] arr = name.split("\\.");
  46. if(arr.length >= 2){
  47. //获取文件的后缀名
  48. String endName = arr[arr.length -1];
  49. //对当前类型的文件进行统计
  50. if(map.containsKey(endName)){
  51. int count = map.get(endName);
  52. count++;
  53. map.put(endName,count);
  54. }else{
  55. map.put(endName,1);
  56. }
  57. }
  58. }else{
  59. //当前file1是文件夹
  60. //递归得到文件夹中的每个文件并存到一个HashMap集合中
  61. HashMap<String,Integer> sonMap = getCount(file1);
  62. //获取sonMap的键值对对象
  63. Set<Map.Entry<String, Integer>> entries = sonMap.entrySet();
  64. //遍历子文件夹下的文件
  65. for (Map.Entry<String, Integer> entry : entries) {
  66. //获取键
  67. String key = entry.getKey();
  68. //获取值
  69. int value = entry.getValue();
  70. //判断文件类型并统计到之前统计的文件个数中
  71. if(map.containsKey(key)){
  72. //如何子文件是之前未存在的文件就新加入到map集合
  73. int count = map.get(key);
  74. count = count + value;
  75. map.put(key,count);
  76. }else{
  77. //如何存在则直接自加
  78. map.put(key,value);
  79. }
  80. }
  81. }
  82. }
  83. }
  84. //返回map
  85. return map;
  86. }
  87. }

运行结果如下:52c21b6394d7443aa237dd68d91e57bc.png

发表评论

表情:
评论列表 (有 0 条评论,94人围观)

还没有评论,来说两句吧...

相关阅读