Search code examples
javabufferedreader

Why BufferedReader reads just 1st row?


This is a method for checking a word in a file, but the method only returns the word is in the first row, if a check a word from a second row it returns false

public static boolean isWord(String file,String word) throws FileNotFoundException,IOException {
    boolean isWord=false;
    BufferedReader read=new BufferedReader(new FileReader(file));
    String content;

    while((content=read.readLine()) != null) {
        if(content.contains(word)) {
            isWord=true;
        } else {
            isWord=false;
        }       
    }
    
}
    return isWord;  
}

Solution

  • Because if the file has 2 rows and the second is not a word, "isWord" is then assigned a "false" value. When you get to the return statement, "false" is the last assigned value and that is why you get a "false" value from the method if the second row has no word in it.