简体   繁体   中英

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;  
}

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM