java练习:
包含迭代器iterator的知识
Map集合的知识
substring
File文件


public class Demo3 {
 private static Map<String, Integer> map = new HashMap<>();// 创建一个map集合
 public static void main(String[] args) {
  Demo3 demo = new Demo3();
  demo.print("d:/myfile");// 写一个方法,反向生成代码(下边方法主体)
  // Java中的Iterator功能比较简单,并且只能单向移动:
  // (1)使用方法iterator()要求容器返回一个Iterator。第一次调用Iterator的next()方法时,它返回序列的第一个元素。
  // 注意:iterator()方法是java.lang.Iterable接口,被Collection继承。
  // (2) 使用next()获得序列中的下一个元素。
  // (3) 使用hasNext()检查序列中是否还有元素。
  // (4) 使用remove()将迭代器新返回的元素删除。
  // Iterator是Java迭代器最简单的实现,为List设计的ListIterator具有更多的功能,它可以从两个方向遍历List,也可以从List中插入和删除元素。
  for (Iterator<Map.Entry<String, Integer>> it = map.entrySet().iterator(); it.hasNext();) {
   // entryset方法可以同时获得ksys和value值
   Entry<String, Integer> next = it.next();
   System.out.println(next.getKey() + "\t" + next.getValue());
  }
 }
 private void print(String string) {
  if (string == null && string.equals("")) {
   System.out.println("路径不能为空!");
   return;
  }
  File file = new File(string);//通过路徑构建文件
  if (!file.exists()) {
   System.out.println("文件不存在!");
   return;
  }
  File[] files = file.listFiles();
  if (files != null && files.length > 0) {
   for (File f : files) {
    if (f != null) {
     if (f.isFile()) {
      String FileName = f.getName();// 获取文件名字
      int index = FileName.lastIndexOf(".") + 1;
      // +1是为了防止出现-1
      String result = FileName.substring(index);
      // substring的截取是前截后不截,只传一个截index之后的所有字符
      if (map.containsKey(result)) {
       //map中的containsKey方法用来检测数据是否存在
       Integer is = map.get(result);
       map.put(result, ++is);
       // 这里只能用++i,++i可以作为左值,可以返回+1后的值
      } else {
       map.put(result, new Integer(1));
       // 由于map方法的键值keys和value一一对应,这么写相当于+1
      }
     } else if (f.isDirectory()) {
      print(f.getAbsolutePath());
      // 递归调用,其中getabsolutePath是绝对路徑
     }
    }
   }
  }
 }
}

java练习

  java练习  

java练习

相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-11-11
  • 2021-12-02
  • 2021-10-21
  • 2021-07-28
猜你喜欢
  • 2022-02-25
  • 2021-10-05
  • 2021-08-31
  • 2022-03-05
  • 2021-09-01
  • 2021-10-30
  • 2021-06-01
相关资源
相似解决方案