Java制作文件内容检索工具


需求:

  该工具能搜索文件夹目录下的所有txt文件的内容,将内容中还有特定词语的文件检索出来

文件夹目录和文件内容如图所示:

  

 

 

 文件内容如下表所示:

2021-02-01.txt 今天我吃了一个苹果
2021-02-05.txt 我今天吃了一个梨
2021-02-07.txt 今天我去动物园玩了
2021-02-08.txt 我今天明白了一个人生道理
2021-02-13.txt 我今天晚饭后吃了一个苹果
2021-02-20.txt 我今天去北京吃了一个梨,太好吃了

 

首先需要设计一个方法,传入文件对象和需要检索的字符串,返回一个是否包含的布尔值

这里如果使用String类的contains方法,需要将整个文件都读入到内存中,浪费系统资源,效率不高。

所以这里考虑采用从前往后边读取边判断的算法:

 

public static boolean searchFile(File f,String keyword) throws IOException {
        FileReader fr = null;
        try {
            fr = new FileReader(f);
        } catch (FileNotFoundException e) {
            System.out.println("文件不存在!");
            return false;
        }
        int c;
        int index = 0;
        while((c=fr.read())!=-1) {
            
            char ch = (char)c;
            
            if(ch == keyword.charAt(index)) {
                
                if(index==(keyword.length()-1)) {
                    fr.close();
                    return true;
                }else {
                    index++;
                    continue;
                }
            }else {
                index=0;
                continue;
            }
        }
        fr.close();
        return false;
    }

利用递归遍历该目录下所有的子文件夹:

public static void recursion(File f,String keyword) throws IOException {
        for(File ff:f.listFiles()) {
            if(ff.isDirectory()) {
                recursion(ff,keyword);
            }else {
                if(searchFile(ff,keyword)) {
                    System.out.println(ff);
                }
            }
        }
    }

运行效果:

 

 

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM