Assume customers.txt is accessible and contains multiple lines.
Which code fragment prints the contents of the customers.txt file?
Click on the arrows to vote for the correct answer
A. B. C. D.D.
The correct answer is D.
Option A uses the Files.find()
method which is used to find files matching a certain criteria recursively in a directory hierarchy. This method returns a Stream<Path>
which represents the paths of the matching files. However, this method cannot be used to read the contents of a file.
Option B also uses the Files.find()
method and suffers from the same issue as option A.
Option C uses the Files.list()
method which returns a Stream<Path>
of all the entries in a directory. Since customers.txt
is a file and not a directory, this method will not return any results.
Option D uses the Files.lines()
method which returns a Stream<String>
of the lines in a file. This method can be used to read the contents of a file line by line. The forEach()
method is then called on the stream to print each line to the console.
Therefore, option D is the correct answer to print the contents of the customers.txt
file.