Java SE 8 Programmer II — Question 103
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
- A. List<String> fc = Files.list(file); fc.stream().forEach (s -> System.out.println(s));
- B. Stream<String> fc = Files.readAllLines (file); fc.forEach (s - > System.out.println(s));
- C. List<String> fc = Files.readAllLines(file); fc.stream().forEach (s -> System.out.println(s));
- D. Stream<String> fc = Files.list (file); fc.forEach (s -> System.out.println(s));
Correct answer: C
Explanation
The correct answer is C because it correctly reads all lines from the file into a List and then streams those lines for printing. Option A is incorrect as it uses Files.list, which is meant for directories, not files. Option B incorrectly uses Stream instead of List, which is not the correct type for storing all lines read from a file. Option D also misuses Files.list, making it unsuitable for reading file content.