Java SE 8 Programmer II — Question 31
The data.doc, data.txt and data.xml files are accessible and contain text.
Given the code fragment:
Stream<Path> paths = Stream.of (Paths. get("data.doc"),
Paths. get("data.txt"),
Paths. get("data.xml"));
paths.filter(s-> s.toString().endWith("txt")).forEach(
s -> {
try {
Files.readAllLines(s)
.stream()
.forEach(System.out::println); //line n1
} catch (IOException e) {
System.out.println("Exception");
}
}
);
What is the result?
data.txt file.
Answer options
- A. The program prints the content of
- B. The program prints: Exception <<The content of the data.txt file>> Exception line n1.
- C. A compilation error occurs at
- D. The program prints the content of the three files.
Correct answer: D
Explanation
The correct answer is D because the filter only allows 'data.txt' to pass through, and the program reads its content without any exceptions. Options A and B are incorrect as they do not accurately describe the output, and option C is wrong because the code will compile successfully.