LearnFrenzy
Sign in Take a free test

File Handling, IO and NIO · Find the Error · Question 4

Error: assigning Files.lines to a List Answer, explanation & discussion

  • Find the error
  • Medium
  • 0 comments
  • Answer explained
  • Moderated community
Question 4 Back to Exercise

The program below does not compile. Which statement correctly describes the problem?

Main.java
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;

public class Main {
    public static void main(String[] args) throws IOException {
        List<String> lines = Files.lines(Path.of("notes.txt"));
        System.out.println(lines.size());
    }
}
  • A notes.txt must exist at compile time
  • B Files.lines returns a Stream<String>, not a List; use Files.readAllLines, or collect the (closed) stream with toList() Correct
  • C List cannot hold Strings
  • D size() does not exist
Correct Answer: Option B

javac: "incompatible types: Stream cannot be converted to List".

Discussion & Comments 0

Share your method, a shortcut, or ask about a step you didn't follow.

No comments yet. Be the first to share your solution!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links