Choose the correct option based on this code segment:
Path path = Paths.get("file.txt"); // READ_FILE lines.forEach(System.out::println);
Assume that a file named "file.txt" exists in the directory in which this code segment is run and has the content "hello".
Which one of these options can be replaced by the text READ_FILE that will successfully read the "file.txt" and print "hello" on the console?.
a) List<String> lines = Files.lines(path); b) Stream<String> lines = Files.lines(path); c) Stream<String> lines = File.readLines(path); d) Stream<String> lines = Files.readAllLines(path);
b)
the lines(Path) method in Files class takes a Path and returns Stream<String>.
hence option b) is the correct answer.
option a) the code segment results in a compiler error because the return type of lines()
method is Stream<String> and not List<String>.
option c) there is no such method named readLines(Path)
in Files that returns a Stream<String> and hence it results in a compiler error.
option d) the readAllLines(Path)
method returns a List<String> and not Stream<String> and hence the given statement results in a compiler error.