What is the output of the following application?
Assume /all-data exists and is accessible within the file system.
package mypkg; /*ww w . java 2 s . com*/ import java.nio.file.*; import java.util.stream.Stream; public class Main { public static Stream<String> readLines(Path p) { try { return Files.lines(p); } catch (Exception e) { throw new RuntimeException(e); } } public static long count(Path p) throws Exception { return Files.list(p) .filter(w -> Files.isRegularFile(w)) .flatMap(s -> readLines(s)) .count(); } public final static void main(String[] day) throws Exception { System.out.print(count(Paths.get("/all-data"))); } }
B.
The program compiles and runs without issue, making Options C and D incorrect.
The program uses Files.list()
to iterate over all files within a single directory.
For each file, it then iterates over the lines of the file and counts the sum.
Option B is the correct answer.
If the count()
method had used Files.walk()
instead of Files.lines()
, then the class would still compile and run, and Option A would be the correct answer.
Note that we had to wrap Files.lines()
in a try-catch block because using this method directly within a lambda expression without a try-catch block leads to a compilation error.