Counts the number of times a particular character, such as e, appears in a file This question came from a Java tutorial online:


  Write an example that counts the number of times a particular character, such as e, appears in a file.


I was just wondering if there is any way to improve this particular solution.

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

public class CountLetter{
    public static void main(String[] args) {
        Path file = Paths.get("/Users/justin/Desktop/Codes Netbean/JavaRandom/xanadu.txt");
        CountLetter cl1 = new CountLetter(file, 'e');
        System.out.println(cl1.count());
    }

    private Path file;
    private char lookFor;

    CountLetter(Path file, char lookFor){
        this.file = file;
        this.lookFor = lookFor;
    }

    private int count(){
        int count = 0;
        try(BufferedReader br = new BufferedReader(new InputStreamReader(Files.newInputStream(file)))){
            String line = null;
            while((line = br.readLine()) != null){
                for(int i = 0; i &lt; line.length(); i++){
                    if(line.charAt(i) == lookFor){
                        count++;
                    }
                }
            }
        } catch (IOException x){
            System.err.println(x);
        }
        return count;
    }
}
If you are using java 8 you can use streams. 

Also IMO for this kind of functionality a static method would me more appropriate.

 public static long countCharacter(Path path, char lookFor) throws IOException {

     try (Stream&lt;String&gt; stream = Files.lines(path)) {

         return stream.flatMapToInt(String::chars)
                      .filter(c -&gt; c == (int) lookFor)
                      .count();
     }
 }