Gentlemen, good afternoon. Please help.

You need to write code to help establish the fact of the word in the file (i.e., the result is stupidly true / false). For example - I have a .txt file, and I need to determine if there is a word in it (for example, "stackoverflow")?

But! In the array can not be written. The task is to establish the fact of the word in the process of reading the file. Tell me where to dig?

PS 1000 apologies to the gentlemen, I incorrectly declared the restrictions: I am allowed to use an array - I cannot accept collections.

    3 answers 3

    Java 8

    public boolean fileContainsWord(String fileName, String word) throws IOException { return new String(Files.readAllBytes(Paths.get(fileName))).contains(word); } 

    Without using contains:

     public boolean fileContainsWord(String fileName, String word) throws IOException { return Files.lines(Paths.get(fileName)) .map(line -> line.split(" *")) .flatMap(Arrays::stream) .distinct() .anyMatch(w -> w.equals(word)); } 
    • Bad decision, if the file is very large, then all this will fall on OOM - Artem Konovalov
    • Frankly, I do not even know what this solution is. It looks great, but I have not yet passed Arrays, map and can not understand what is happening here. I would like to suggest how this can be implemented at the level of a completely beginner. - Dmitriy

    My fault - I forgot to clarify. I am prohibited from using the contains (...) and indexOf (...) methods. I suppose they demand that I implement the search using either the Scanner or something from Readera (a)

      I did this:

       boolean isContains = Files .lines(Paths.get("file.txt")) .anyMatch(e->e.contains("word")); 

      I do not understand how you can determine the content without using contains . You can write your analog instead, but the essence is the same.

      • Probably they want to check the ability to read the file character by character (buffered or not) and sequential comparison. - Morewind
      • @Morewind or implementation of some known search algorithms. - Artem Konovalov
      • This is most likely. Help out - show at least in which direction to dig, and then I'm on the textbooks. - Dmitry