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?
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?
To print the content of the courses.txt file, you should use a method that reads the file line by line and processes each line. The correct method to use in this scenario is Files.lines(file), which returns a Stream of lines from the file. You can then use the forEach method to print each line to the console. This method handles the I/O operations efficiently and works seamlessly with the Path object.
public class FileLinesMain { public static void main(String[] args) throws IOException { Path file = Paths.get ("courses.txt"); Files.lines(file); Stream<String> fc = Files.lines (file); fc.forEach (s -> System.out.println(s)); } } Answer : D
Answer is D. C must like is List<String> lines = Files.readAllLines(file);lines.stream().forEach(System.out::println);
Both C and D work.
Yes thats correct.We usually use readAllLines() for large files and lines() for small files.
Except C does not reference the Files class, and its not implied in the question that it is statically imported
Answer is D
D is correct.