【问题标题】:Searching for string in file and returning that specific line在文件中搜索字符串并返回该特定行
【发布时间】:2016-02-29 09:25:39
【问题描述】:

我正在研究学生注册系统。我有一个包含学生姓名、学生编号和学生成绩的文本文件存储在每一行中,例如:

 name1,1234,7
 name2,2345,8
 name3,3456,3
 name4,4567,10
 name5,5678,6

如何搜索一个名字然后返回整个句子?查找名称时没有任何匹配项。

我当前的代码如下所示:

public static void retrieveUserInfo()
{
    System.out.println("Please enter username"); //Enter the username you want to look for
    String inputUsername = userInput.nextLine();


    final Scanner scanner = new Scanner("file.txt");
    while (scanner.hasNextLine()) {
       final String lineFromFile = scanner.nextLine();
       if(lineFromFile.contains(inputUsername)) { 
           // a match!
           System.out.println("I found " +inputUsername+ " in file " ); // this should return the whole line, so the name, student number and grade
           break;
       }
       else System.out.println("Nothing here");
    }

【问题讨论】:

  • 语言 = Java?如果是这样,请包含在标签中。此外,lineFromFile 似乎已经包含您的整行,所以只需打印它....
  • 添加了标签并打印了 lineFromFile 但仍然找不到匹配项。这可能与文本文件中的逗号分隔有关吗?
  • 如果在if 语句之后添加System.out.println(lineFromFile);,会得到什么输出?
  • while (scanner.hasNextLine()) { final String lineFromFile =scanner.nextLine(); if(lineFromFile.contains(inputUsername)) { // 匹配! System.out.println(lineFromFile);休息; } else System.out.println("这里没有");此处不返回任何内容
  • 你知道这种greping是区分大小写的吗?您可能需要使用lineFromFile.toLowerCase().contains(inputUserName.trim().toLowerCase())

标签: java file search text line


【解决方案1】:

问题在于 Scanner(String) 构造函数:

public Sc​​anner(java.lang.String source)

构造一个新的 Scanner 来生成从 指定的字符串。

参数:source - 要扫描的字符串

它对文件一无所知,只知道字符串。所以,这个Scanner 实例可以给你的唯一一行(通过nextLine() 调用)是file.txt

简单的测试是:

Scanner scanner = new Scanner("any test string");
assertEquals("any test string", scanner.nextLine());

您应该使用Scanner 类的其他构造函数,例如:

Scanner(InputStream)
Scanner(File)
Scanner(Path)

【讨论】:

    【解决方案2】:

    你已经有了保存整行的变量。像这样打印它:

    while (scanner.hasNextLine()) {
           final String lineFromFile = scanner.nextLine();
           if(lineFromFile.contains(inputUsername)) { 
               // a match!
               System.out.println("I found " +lineFromFile+ " in file " ); 
               break;
           }
           else System.out.println("Nothing here");
        }
    

    【讨论】:

      猜你喜欢
      • 2012-09-09
      • 1970-01-01
      • 2014-02-12
      • 2021-01-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-10-07
      相关资源
      最近更新 更多