Find a string (or a line) in a txt File Java
file, java, string
Solution
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<String> 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
}
}
Problem
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 that txt file for the String "omar", if it doesn't exist, simply display "doesn't exist". I tried the function String.endsWith() or String.startsWith(), but that of course displays "doesn't exist" 3 times. I started java only 3 weeks ago, so I am a total newbie...please bear with me. thank you.