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 questionsThe 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.
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.
- 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.
Keep practicing
Take the free 1Z0-809 practice test
Ten exam-style questions with answers and explanations, plus the exam facts and study guides.
More questions
Other 1Z0-809 practice questions
- Question 2Given: class Student { String course, name, city; public Student (String name, String cou…
- Question 3Given: class Worker extends Thread { CyclicBarrier cb; public Worker(CyclicBarrier cb) { …
- Question 5Given that /green.txt and /colors/yellow.txt are accessible, and the code fragment: Path …
- Question 6Given the code fragment:List<String> empDetails = Arrays.asList(“100, Robin, HR”,“200, Ma…
- Question 7Given the code fragment: List str = Arrays.asList (“my”, “pen”, “is”, “your’, “pen”); Pre…
- Question 8Which two reasons should you use interfaces instead of abstract classes? (Choose two.)
