在文件中搜索字符串并在找到时返回该字符串 [英] Search a file for a String and return that String if found

查看:17
本文介绍了在文件中搜索字符串并在找到时返回该字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在 txt 文件中搜索用户输入的字符串,然后将该字符串返回到控制台.我在下面写了一些不起作用的代码,但我希望它可以说明我的观点...

How can you search through a txt file for a String that the user inputs and then return that String to the console. I've written some code that doesn't work below, but I hope it can illustrate my point...

public static void main(String[] args) {
  searchforName();
}

   private static void searchForName() throws FileNotFoundException {
    File file = new File("leaders.txt");
    Scanner kb = new Scanner(System.in);
    Scanner input = new Scanner(file);

    System.out.println("Please enter the name you would like to search for: ");
    String name = kb.nextLine();


    while(input.hasNextLine()) {
        System.out.println(input.next(name));
    }
}

leaders.txt"文件包含一个名字列表.

The "leaders.txt" file contains a list of names.

推荐答案

您可以创建一个单独的 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.

这篇关于在文件中搜索字符串并在找到时返回该字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆