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?
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 = readAllLines(file);
fc.stream().forEach (s -> System.out.println(s));
D.
Stream<String> fc = Files.lines(file);
fc.forEach (s -> System.out.println(s));
題解
選項 A,Files 類別的 list 方法會回傳 Stream<Path>物件,所以會編譯錯誤。
選項 B,Files 類別的 readAllLines 方法會回傳 List<String>物件,所以會編譯錯誤。
選項 C,readAllLines 方法前應該指定 Files 類別。
選項 D,正確答案。
