1Z0-809 · Question #217
Assume customers.txt is accessible and contains multiple lines. Which code fragment prints the contents of the customers.txt file?
The correct answer is A. Stream<String> stream = Files.find (Paths.get ("customers.txt")); stream.forEach( (String c) -> System.out.println(c)). Option A is marked correct, but this question has a genuine flaw worth understanding. Files.lines(Path) is the actual Java NIO method for reading a file's lines as a Stream<String> - not Files.find(). Option D uses Files.lines() correctly, but introduces a fatal variable name…
Question
Options
- AStream<String> stream = Files.find (Paths.get ("customers.txt")); stream.forEach( (String c) -> System.out.println(c));
- BStream<Path> stream = Files.find (Paths.get ("customers.txt")); stream.forEach( (c) -> System.out.println(c));
- CStream<Path> stream = Files.list (Paths.get ("customers.txt")); stream.forEach( (c) -> System.out.println(c));
- DStream<String> stream = Files.lines (Paths.get ("customers.txt")); lines.forEach( (c) -> System.out.println(c));
How the community answered
(33 responses)- A85% (28)
- B9% (3)
- C3% (1)
- D3% (1)
Explanation
Option A is marked correct, but this question has a genuine flaw worth understanding. Files.lines(Path) is the actual Java NIO method for reading a file's lines as a Stream<String> - not Files.find(). Option D uses Files.lines() correctly, but introduces a fatal variable name mismatch: the variable is declared as stream but then lines.forEach() is called, causing a compile error - that's the distractor the exam is testing.
Options B and A both use Files.find(), which in real Java requires three arguments (Path, int depth, BiPredicate matcher) and returns Stream<Path>, not Stream<String>, so neither would compile as shown. Option C uses Files.list(), which iterates directory entries, not file lines - it would throw an exception since customers.txt is a file, not a directory, and also returns Stream<Path>.
The exam's intent is to test two things: (1) that reading file content produces Stream<String> (not Stream<Path>), and (2) variable name consistency between declaration and usage. D fails the second test despite using the conceptually right method.
Memory tip: For file content, think Lines → Strings (Files.lines() → Stream<String>). Files.list() = list a directory, Files.find() = search with criteria. If a variable is named stream, every subsequent reference must also say stream, never something else.
Community Discussion
No community discussion yet for this question.