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

前端 未结 5 938
忘掉有多难
忘掉有多难 2020-12-09 06:03

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 tha

5条回答
  •  轮回少年
    2020-12-09 06:46

    You can do this with Files.lines:

    try(Stream 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.

提交回复
热议问题