Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

string

file

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.

like image 683
user3040333 Avatar asked Dec 06 '13 07:12

user3040333


People also ask

How do you find a specific string in Java?

You can search for a particular letter in a string using the indexOf() method of the String class. This method which returns a position index of a word within the string if found. Otherwise it returns -1.

How do you check if there is another line in a file Java?

The hasNextLine() is a method of Java Scanner class which is used to check if there is another line in the input of this scanner. It returns true if it finds another line, otherwise returns false.


3 Answers

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

      }

 }
like image 107
Ruchira Gayan Ranaweera Avatar answered Oct 26 '22 11:10

Ruchira Gayan Ranaweera


use String.contains(your search String) instead of String.endsWith() or String.startsWith()

eg

 str.contains("omar"); 
like image 1
Prabhakaran Ramaswamy Avatar answered Oct 26 '22 09:10

Prabhakaran Ramaswamy


You can go other way around. Instead of printing 'does not exist', print 'exists' if match is found while traversing the file and break; If entire file is traversed and no match was found, only then go ahead and display 'does not exist'.

Also, use String.contains() in place of str.startsWith() or str.endsWith(). Contains check will search for a match in the entire string and not just at the start or end.

Hope it makes sense.

like image 1
Ankur Shanbhag Avatar answered Oct 26 '22 10:10

Ankur Shanbhag