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

Viewed 80424

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.

5 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

      }

 }

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

eg

 str.contains("omar"); 

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.

Read the content of the text file: http://www.javapractices.com/topic/TopicAction.do?Id=42

And after that just use the textData.contains(user_input); method, where textData is the data read from the file, and the user_input is the string that is searched by the user

UPDATE

public static StringBuilder readFile(String path) 
 {       
        // Assumes that a file article.rss is available on the SD card
        File file = new File(path);
        StringBuilder builder = new StringBuilder();
        if (!file.exists()) {
            throw new RuntimeException("File not found");
        }
        BufferedReader reader = null;
        try {
            reader = new BufferedReader(new FileReader(file));
            String line;
            while ((line = reader.readLine()) != null) {
                builder.append(line);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

       return builder;
    }

This method returns the StringBuilder created from the data you have read from the text file given as parameter.

You can see if the user input string is in the file like this:

int index = readFile(filePath).indexOf(user_input);
        if ( index > -1 )
            System.out.println("exists");

You can do this with Files.lines:

try(Stream<String> lines = Files.lines(Paths.get("...")) ) {
    if(lines.anyMatch("omar"::equals)) {
  //or lines.anyMatch(l -> l.contains("omar"))
        System.out.println("found");
    } else {
        System.out.println("not found");
    }
}

Note that it uses the UTF-8 charset to read the file, if that's not what you want you can pass your charset as the second argument to Files.lines.

Related