Search a file for a String and return that String if found

后端 未结 3 1036
野性不改
野性不改 2020-12-18 00:38

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 h

3条回答
  •  暖寄归人
    2020-12-18 00:44

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

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

提交回复
热议问题