1Z0-809 practice question 4 of 25

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?

Full set: 196 questions
Answer options
A: List fc = Files.list(file);fc.stream().forEach (s - > System.out.println(s));
B: Stream fc = Files.readAllLines (file);fc.forEach (s - > System.out.println(s));
C: List fc = readAllLines(file);fc.stream().forEach (s - > System.out.println(s));
D: Stream fc = Files.lines (file);fc.forEach (s - > System.out.println(s)); Correct answer
Correct Answer:
D. Stream fc = Files.lines (file);fc.forEach (s - > System.out.println(s));
Explanation

The Files.lines(Path) method reads all lines from a file and returns them as a Stream. This is the most direct and idiomatic way in Java 8 to process a file's content line-by-line using the Stream API. The returned stream can then be consumed by a terminal operation like forEach to print each line. This approach is also memory-efficient for large files as it reads lines lazily.

Why Incorrect

A. Files.list() is used for listing the contents of a directory, not for reading a file. It would throw a NotDirectoryException at runtime.
B. Files.readAllLines() returns a List, not a Stream. Assigning its result to a Stream variable causes a compilation error.
C. The method call readAllLines(file) is a compilation error. The correct call is Files.readAllLines(file), as it is a static method of the Files class.

References

- Java SE 8 Platform API Specification, java.nio.file.Files.lines(Path path). The documentation confirms it returns a Stream with the lines from a file.

- Oracle, The Java™ Tutorials, "Reading, Writing, and Creating Files". This tutorial presents Files.lines as the standard method for reading a text file as a stream of lines.

Scroll to Top