简体   繁体   English

如何在Java中使用BufferedReader在.txt文件中查找特定字符串

[英]How to find a specific string in .txt file using BufferedReader in Java

I have a task to search all .txt files for a specific word and then print all files containing that word. 我的任务是搜索所有.txt文件中的特定单词,然后打印包含该单词的所有文件。 I have this code which finds all .txt files, and I just need to add check if that word is in, but with using BufferedReader import. 我有这段代码可以找到所有.txt文件,我只需要添加检查该单词是否在其中,但是要使用BufferedReader导入。 I'm new in Java and I'd be happy if you help me. 我是Java的新手,如果您能帮助我,我会很高兴。

package thenewboston.tutorials;
import java.io.File;
import java.io.FilenameFilter;
import java.io.BufferedReader;

public class apples30 {
    public static void main(String[] args) {
        File folder = new File("D:\\test");
        FilenameFilter filter = new FilenameFilter() {

            @Override
            public boolean accept(File dir, String name) {
                if(name.lastIndexOf('.')>0) {
                      int lastIndex = name.lastIndexOf('.');
                      String str = name.substring(lastIndex);
                      if(str.equals(".txt")) {
                         return true;
                      }
                   }
                return false;
            }
        };
        File[] listOfFiles = folder.listFiles(filter);

        for(File x: listOfFiles) {
            System.out.println(x.getName());
        }
    }
}

This is how my code looks now. 这就是我的代码现在的样子。

您可以阅读文件并使用.contains(“ specific word”)(一个字符串方法,如果该字符串包含该特定单词,则将返回true)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM