Wednesday, August 24, 2016

Some useful and concise operations upon a given text file written in Java 8

The following "contains" method represents a concise way of checking whether a word exists or not within a file:

public static boolean contains(Path p, String word) {
try {
return new String(Files.readAllBytes(p), StandardCharsets.UTF_8).contains(word);
} catch (IOException ex) {
return false;
}
}

Here is another method that counts the number of words within a file using Java 8's new feature "parallel stream":

public static long countNumberOfWords(Path p) throws IOException {
return Arrays.asList(new String(Files.readAllBytes(p), StandardCharsets.UTF_8).split("[\\P{L}]+"))
.parallelStream().count();
}

No comments:

Post a Comment