10

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.

user3040333
  • 105
  • 1
  • 1
  • 6

5 Answers5

6

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

      }

 }
Ruchira Gayan Ranaweera
  • 34,993
  • 17
  • 75
  • 115
1

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

eg

 str.contains("omar"); 
Prabhakaran Ramaswamy
  • 25,706
  • 10
  • 57
  • 64
1

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.

Ankur Shanbhag
  • 7,746
  • 2
  • 28
  • 38
0

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");
Hitman
  • 588
  • 4
  • 10
  • instead of textData, should I put the name of the file? for example File file = new File(); then put "file" instead of textData ? – user3040333 Dec 06 '13 at 07:47
0

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.

Alex - GlassEditor.com
  • 14,957
  • 5
  • 49
  • 49