且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在文件中搜索字符串并在找到时返回该字符串

更新时间:2023-11-07 20:05:46

您可以创建一个单独的 Scanner 来逐行读取文件并以这种方式进行匹配...

You can create a seperate Scanner to read the file line by line and do a match that way...

final Scanner scanner = new Scanner(file);
while (scanner.hasNextLine()) {
   final String lineFromFile = scanner.nextLine();
   if(lineFromFile.contains(name)) { 
       // a match!
       System.out.println("I found " +name+ " in file " +file.getName());
       break;
   }
}

关于您应该使用Scanner 还是BufferedReader 来读取文件,请阅读此答案.

With regards to whether you should use a Scanner or a BufferedReader to read the file, read this answer.