Find a string (or a line) in a txt File Java

前端 未结 5 939
忘掉有多难
忘掉有多难 2020-12-09 06:03

let\'s say I have a txt file containing:

john
dani
zack

the user will input a string, for example \"omar\" I want the program to search tha

5条回答
  •  不思量自难忘°
    2020-12-09 06:46

    Just read this text file and put each word in to a List and you can check whether that List contains your word.

    You can use Scanner scanner=new Scanner("FileNameWithPath"); to read file and you can try following to add words to List.

     List list=new ArrayList<>();
     while(scanner.hasNextLine()){
         list.add(scanner.nextLine()); 
    
     }
    

    Then check your word is there or not

    if(list.contains("yourWord")){
    
      // found.
    }else{
     // not found
    }
    

    BTW you can search directly in file too.

    while(scanner.hasNextLine()){
         if("yourWord".equals(scanner.nextLine().trim())){
            // found
            break;
          }else{
           // not found
    
          }
    
     }
    

提交回复
热议问题