java实现搜索文件夹中所有文件包含的关键字的文件路径(递归搜索)

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

public class Test {
    
    //计算文件数量
    public static int count = 0;
    
    //关键字
    public static String keyWords = "人员姓名";
    
    //搜索后查询到的文件路径汇总文件地址
    public static String searchedFilePath = "G:/Document/HongDaXingYe/SearchedDir/searchedFile.txt";
    
    public static File searchedFile = new File(searchedFilePath);
    
    public static FileOutputStream fos = null;
    
    public static void main(String[] args){
        String path = "G:/Document/HongDaXingYe/Project/oa/workflow/home/weaver/ecology/workflow/";
//        String path = "G:/Document/HongDaXingYe/Project/oa/workflow/home/weaver/ecology/workflow/mode/";
        try{
            fos = new FileOutputStream(searchedFile);
            if(!searchedFile.exists()){
                searchedFile.createNewFile();
            }
        }catch(Exception e){
            e.printStackTrace();
        }
        File file = new File(path);
        File[] files = file.listFiles();
        getFiles(files);
        try {
            fos.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        System.out.println(count);
    }
    
    //递归搜索文件
    public static void getFiles(File[] files){
        FileInputStream fis = null;
        try{
            for(File file : files){
                count++;
                if(file.isDirectory()){
                    getFiles(file.listFiles());
                }else{
                    StringBuilder sb = new StringBuilder();
                    byte[] bytes = new byte[1024];
                    fis = new FileInputStream(file);
                    int len = 0;
                    while((len = fis.read(bytes)) != -1){
                        sb.append(new String(bytes, 0, len));
                    }
                    fis.close();
                    if(sb.indexOf(keyWords) >= 0){
                        System.out.println(file.getAbsolutePath());
                        fos.write((file.getAbsolutePath() + System.lineSeparator()).getBytes());
                        fos.flush();
                    }
                }
            }
        }catch(Exception e){
            e.printStackTrace();
        }
    }
    
    
}
2015年10月-2016年3月 总计:5个月.
2016年11月-2017年6月 总计:7个月.
2017年7月-2018年4月 总计:9个月.
2018年5月-2018年5月 总计:1个月.
2018年6月-2018年12月 总计:6个月.
2019年1月-2019年12月 总计11个月.
2020年2月-2021年2月 总计13个月.
所有总计:5+7+9+1+6+11+13=52个月(4年4个月).
本人认同二元论.我是理想主义者,现实主义者,乐观主义者,有一定的完美主义倾向.不过,一直都是咸鱼(菜鸟),就算有机会,我也不想咸鱼翻身.(并不矛盾,因为具体情况具体分析)
英语,高等数学,考研,其他知识学习打卡交流QQ群:946556683
原文地址:https://www.cnblogs.com/JimmySeraph/p/9412270.html