Skip to content

Instantly share code, notes, and snippets.

@Ribesg
Created February 20, 2013 17:56
Show Gist options
  • Save Ribesg/4997533 to your computer and use it in GitHub Desktop.
Save Ribesg/4997533 to your computer and use it in GitHub Desktop.
// The call is always made with an existing file
public static HashMap<Character, Integer> countCharactersInFile(Path pathToFile) {
final HashMap<Character, Integer> characterMap = new HashMap<Character, Integer>();
try (BufferedReader reader = Files.newBufferedReader(pathToFile, Charset.defaultCharset())) {
char c;
while (reader.ready()) {
c = (char) reader.read();
if (characterMap.containsKey(c)) {
characterMap.put(c, characterMap.get(c) + 1);
} else {
characterMap.put(c, 1);
}
}
} catch (final IOException e) {
e.printStackTrace();
System.exit(-1);
}
return characterMap;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment