Dave Jackson
Dave Jackson

Reputation: 837

How to check a word in a file there is or not the word

I was there a problem with my code, where I need a function to check whether there is the word I'm looking for or not in a file, if there is then it will return true, and if it fails will return false.

public void MyFunction(){
    String theWord = "Im very handsome";
    File theFile = new File("/home/rams/Desktop/tes.txt");
    if(CheckWord(theWord, theFile)){
      // so I will continue my coding, while I stuck :-(
    }
}

public void CheckWord(String theWord, File theFile){
   // what the code to search a word, which the word is variable theWord, the file is variable theFile
   // return true if in file there a word
   // return false if in file there not a word
   // thanks my brother
}

Thanks for advance.

Upvotes: 1

Views: 2566

Answers (2)

anubhava
anubhava

Reputation: 785531

You can use this one-liner method:

public boolean CheckWord(String theWord, File theFile) {
    return (new Scanner(theFile).useDelimiter("\\Z").next()).contains(theWord);
}

Upvotes: 1

Evans
Evans

Reputation: 1599

Since this seems a homework assignment, I won´t give you the code of the solution. You need to:

  1. Your function CheckWord must return a boolean instead of void
  2. Read the text in the file (What is simplest way to read a file into String?)
  3. Compare the text in the file with your word (http://www.vogella.com/articles/JavaRegularExpressions/article.html or http://docs.oracle.com/javase/6/docs/api/java/lang/String.html)
  4. Return true or false depending on the result of the comparison

Upvotes: 1

Related Questions