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,正确答案。
