Java SE 8 Programmer II — Question 90
Assume customers.txt is accessible and contains multiple lines.
Which code fragment prints the contents of the customers.txt file?
Answer options
- A. Stream<String> stream = Files.find (Paths.get ("customers.txt")); stream.forEach((String c) -> System.out.println(c));
- B. Stream<Path> stream = Files.find (Paths.get ("customers.txt")); stream.forEach( c) -> System.out.println(c));
- C. Stream<Path> stream = Files.list (Paths.get ("customers.txt")); stream.forEach( c) -> System.out.println(c));
- D. Stream<String> lines = Files.lines (Paths.get ("customers.txt")); lines.forEach( c) -> System.out.println(c));
Correct answer: D
Explanation
The correct answer is D because the Files.lines method is specifically designed to read all lines from a file as a Stream of Strings. Options A and B incorrectly use Files.find, which is not intended for reading file contents, while option C uses Files.list, which returns a Stream of Paths instead of the file lines.