Counting the occurrences of a string in each file I am trying to find a phrase or a string in file and count the number of occurrences of that string:

 private static HashMap&lt;String, Integer&gt; bruteForceSearch(
      String stringToLookFor, List&lt;File&gt; list) throws IOException {

    HashMap&lt;String, Integer&gt; result = new HashMap&lt;String, Integer&gt;();
    for (File file : list) {
      String fileName = file.getName();
      // System.out.println(fileName);
      FileInputStream fstream = new FileInputStream(file);
      BufferedReader in = new BufferedReader(new InputStreamReader(fstream));
      String readLine = "";
      int count = 0;
      while ((readLine = in.readLine()) != null) {
        String[] words = readLine.split(" ");
        for (String text : words) {
          if (text.equalsIgnoreCase(stringToLookFor)) {
            count++;
          }
        }
      }
      if (count != 0) {
        result.put(fileName, count);
      }

      in.close();
    }

    return result;

  }


Are there any improvements to do in my code? Please let me know.
The first comment is that your code doesn't handle exceptions at all. You open a FileInputStream but you do not close it in case of exceptions. This can lead to a resource leak. Beginning with Java 7, you can use the try-with-resources statement to make sure that all open streams are closed properly. Instead of having

FileInputStream fstream = new FileInputStream(file);
BufferedReader in = new BufferedReader(new InputStreamReader(fstream));


you would have

try (FileInputStream fstream = new FileInputStream(file);
     BufferedReader in = new BufferedReader(new InputStreamReader(fstream));
) {
    // do the rest here
}


When the try block will finish, whether normally or exceptionally, all the streams that were opened in the try initialization block will be closed.
You don't need to wrap your stream into a InputStreamReader and a FileInputStream. You can just use a FileReader that does this already, turning your code into

try (BufferedReader in = new BufferedReader(new FileReader(file))) {
    // do the rest here
}


When the BufferedReader will be closed, it will also close the underlying FileReader.
You should prefer to program against interfaces and not implementation. Consider changing this

HashMap&lt;String, Integer&gt; result = new HashMap&lt;String, Integer&gt;();


to this

Map&lt;String, Integer&gt; result = new HashMap&lt;String, Integer&gt;();


or even

Map&lt;String, Integer&gt; result = new HashMap&lt;&gt;();


since you don't need to reiterate the type parameters since Java 7. In the same way, your method could return a Map&lt;String, Integer&gt; instead of a HashMap&lt;String, Integer&gt;.
Try to remove commented out code like // System.out.println(fileName);.