题目:**18.30 (找出单词)
编写一个程序,递归地找出某个目录下的所有文件中某个单词出现的次数。从命令行如下传递参数:
java Exercise18_30 dirName word
-
习题思路
- (读取路径方法)和18.28题差不多,把找到文件后变量计数+1改成调用读取文件单词在文件内出现的次数即可(调用读取文件方法)。Java语言程序设计基础篇_编程练习题*18.28 (非递归目录大小)-CSDN博客
- (读取文件方法)传入文件和单词,逐行读取文件,如果找到单词,则计数变量+1.
- (main方法)读取传入的路径和单词,调用读取路径方法。
-
代码示例
编程练习题18_30WordCount.java
package chapter_18;import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Scanner;public class 编程练习题18_30WordCount {public static void main(String[] args) throws FileNotFoundException{if(args.length != 2) {System.out.println("Usage: java 编程练习题18_30WordCount dirName word");System.exit(0);}String path = args[0];String word = args[1];File file = new File(path);int count = readPath(file, word);System.out.println("The string "+word+" appears a total of "+count+" times.");}public static int readPath(File file,String word) throws FileNotFoundException{int count = 0;ArrayList<File> files = new ArrayList<File>();files.add(file);while(!files.isEmpty()) {ArrayList<File> newList = new ArrayList<File>();for(File f : files) {if(f.isFile())count+=readFile(f, word);else {File[] fileList = f.listFiles();if(fileList != null) {for(File f2:fileList){if(f2.isDirectory())newList.add(f2);else count += readFile(f2, word);}}}}files = newList;}return count;}public static int readFile(File file,String word)throws FileNotFoundException {int count = 0;try(Scanner input = new Scanner(file)){while(input.hasNextLine()) {String line = input.nextLine();if(line.contains(word))count++;}}return count;}}
-
输出结果
javac 编程练习题18_30WordCount.javajava chapter_18/编程练习题18_30WordCount C:/Users/Lenovo/eclipse-workspace/JavaFX/src public