指定根目录下,查找根目录所有文件中,统计文件中给定单词的出现次数。运用了Java11 引入的Path类和其静态方法of() 。 Java8中Stream流的 filter()筛选,collect()

本篇讲述了在指定根目录下,查找根目录所有文件中,统计文件中给定单词的出现次数

运用了Java11 引入的Path类和其静态方法of()Java8Stream流的 filter()筛选,collect() 收集 ,forEach()遍历。 Files.walk()遍历目录和文件。

Path.of()方法接收一个表示路径的字符串作为参数,并返回一个Path对象。

Path of = Path.of("C:\\Users\\23988\\IdeaProjects\\Multithreaded\\src\\com\\executors");
System.out.println(of);

运行结果:

在这里插入图片描述

Files.walk(of)是Java中用于遍历目录和文件的方法之一。它返回一个Stream<Path>对象,该对象包含了指定根目录下的所有子目录和文件的路径。

Path of = Path.of("C:\\Users\\23988\\IdeaProjects\\Multithreaded\\src\\com\\executors");
Stream<Path> entries = Files.walk(of);//entries 条目
entries.forEach(System.out::println);//用Stream.forEach进行遍历打印

路径下的文件:

在这里插入图片描述

运行结果:

在这里插入图片描述

filter() :筛选

filter(Files::*isRegularFile*): 筛选出普通文件

filter(Files::*isRegularFile*).forEach(System.*out*::println);筛选出普通文件,并使用forEach()方法打印每个文件的路径。

 Path of = Path.of("C:\\Users\\23988\\IdeaProjects\\Multithreaded\\src\\com\\executors");
Stream<Path> entries = Files.walk(of);//entries 条目
entries.filter(Files::isRegularFile).forEach(System.out::println);

运行结果:

在这里插入图片描述

collect(Collectors.toSet())是一个终端操作,将筛选后的文件路径结果收集到一个Set集合中。

Path of = Path.of("C:\\Users\\23988\\IdeaProjects\\Multithreaded\\src\\com\\executors");
Stream<Path> entries = Files.walk(of);//entries 条目
Set<Path> set = entries.filter(Files::isRegularFile).collect(Collectors.toSet());
for (Path file:set) {//forEach语句
    System.out.println("file"+file);
}

运行结果:

在这里插入图片描述

Scanner对象的方法读取文件中的数据,并将其打印出来。 需要结合hasNext(),next(),nextLine()等方法

haNext():判断遍历的下一个对象是否为空

next():遍历一句

nextLine():遍历一行

Path of = Path.of("C:\\Users\\23988\\IdeaProjects\\Multithreaded\\src\\com\\executors");
Stream<Path> entries = Files.walk(of);//entries 条目
Set<Path> set = entries.filter(Files::isRegularFile).collect(Collectors.toSet());
for (Path file:set) {
	System.out.println("file"+file);
	Scanner in = new Scanner(file);
	while (in.hasNext()){
   		String next = in.nextLine();
   		System.out.println("next:"+next);
	}
}

运行结果:
在这里插入图片描述

在这里插入图片描述

in.next().equals("import"):查看遍历的结果中是否有improt这个字符串。

最后打印出在指定根目录下的文件中,import出现的次数。在这里就是找那四个java文件中(内容),import出现的次数。

Path of = Path.of("C:\\Users\\23988\\IdeaProjects\\Multithreaded\\src\\com\\executors");
int count=0;
Stream<Path> entries = Files.walk(of);//entries 条目
Set<Path> set = entries.filter(Files::isRegularFile).collect(Collectors.toSet());
for (Path file:set) {
    System.out.println("file"+file);
    Scanner in = new Scanner(file);
     while (in.hasNext()){
         if (in.next().equals("import")){
              count++;
          }
      }
}
System.out.println("count:"+count);

运行结果:
在这里插入图片描述

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值