Java SE 8 Programmer II — Question 56

Given the code fragment:
Path file = Paths.get ("courses.txt");
// line n1
Assume the courses.txt is accessible.
Which code fragment can be inserted at line n1 to enable the code to print the content of the courses.txt file?

Answer options

Correct answer: D

Explanation

The correct answer is D because Files.lines(file) provides a stream of lines from the file, which can be directly printed using forEach. Option A is incorrect because Files.list() returns a stream of file paths, not lines from the file. Option B is incorrect as Files.readAllLines() returns a List, not a Stream. Option C fails for the same reason as B, as it attempts to use readAllLines without the proper class reference.