java查找一个字符串在一个文件夹下出现的次数与路径

献给那些在一堆文本文件中找不到自己想要的字段的同行

package util;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;

/**
 * @Author Daniel
 * @Description 自己写的一个util,有需要的自取
 **/
public class FindWords {
    //总数
    public static int count = 0;

    public static void main(String[] args) {
        findFile(new File("F:\\test\\test2"), "a");
    }

    public static void findFile(File file, String word) {
        File[] listFiles = file.listFiles();
        for (int i = 0; i < listFiles.length; i++) {
            if (listFiles[i].isDirectory())
                //如果是文件夹则进行递归
                findFile(listFiles[i], word);
            //如果文件存在或者能读则开始检索
            if (listFiles[i].exists() || listFiles[i].canRead()) {
                try {
                    int j = 0, k = 0, ch = 0;
                    String str = null;
                    FileReader in = new FileReader(listFiles[i]);
                    while ((ch = in.read()) != -1) {
                        //拼接一次比较一次
                        str += (char) ch;
                    }
                    if (str != null) {
                        while (str.indexOf(word, j) != -1) {
                            k++;
                            j = str.indexOf(word, j) + 1; // 返回第一次出现的指定子字符串在此字符串中的索引
                        }
                    }
                    if (k > 0) {
                        System.out.println("路径:" + listFiles[i].getAbsolutePath() + "中有" + k + "个" + word);
                        count++;
                    }
                    in.close();
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

        if (count != 0) {
            System.out.println("“" + word + "”以一共在" + count + "个文件中出现了");
        } else {
            System.out.println("“" + word + "”不存在!");
        }
    }
}

发布了101 篇原创文章 · 获赞 265 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/a805814077/article/details/103668019