在文件中搜索String,如果找到则返回该String [英] Search a file for a String and return that String if found

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

问题描述

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

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.

推荐答案

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

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;
   }
}

关于是否应该使用扫描仪 BufferedReader 来读取文件,请阅读回答

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

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

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