Java 8 Streams read file
In Java 8 we can use Files.lines
to read file into stream and do manipulations.
Let’s say we want to count the number of unique words in the file.
countries.txt
USA Canada
Germany England USA
Italy Germany
try (Stream lines =
Files.lines(Paths.get("C:\\countries.txt"), Charset.defaultCharset())) {
lines.flatMap(line -> Arrays.stream(line.split(" ")))
.distinct().forEach(System.out::println);
} catch (IOException e) {
e.printStackTrace();
}
//output
USA
Canada
Germany
England
Italy