nerdexam
Oracle

1Z0-809 · Question #87

Given the code fragment: Stream<Path> files = Files.walk(Paths.get(System.getProperty("user.home"))); files.forEach (fName -> { //line n1 try { Path aPath = fName.toAbsolutePath(); //line n2…

The correct answer is A. All files and directories under the home directory are listed along with their attributes. Files.walk() performs a recursive, depth-first traversal of the entire directory tree starting at the given path, yielding every Path it encounters - both files and subdirectories. Since the code reads BasicFileAttributes for each path and prints them without error, option A is…

Question

Given the code fragment: Stream<Path> files = Files.walk(Paths.get(System.getProperty("user.home"))); files.forEach (fName -> { //line n1 try { Path aPath = fName.toAbsolutePath(); //line n2 System.out.println(fName + ":"); Files.readAttributes (aPath, Basic.File.Attributes.class) .creationTime () ; } catch (IOException ex) { ex.printStackTrace(); } }); What is the result?

Options

  • AAll files and directories under the home directory are listed along with their attributes.
  • BA compilation error occurs at line n1.
  • CThe files in the home directory are listed along with their attributes.
  • DA compilation error occurs at line n2.

How the community answered

(57 responses)
  • A
    84% (48)
  • B
    5% (3)
  • C
    2% (1)
  • D
    9% (5)

Explanation

Files.walk() performs a recursive, depth-first traversal of the entire directory tree starting at the given path, yielding every Path it encounters - both files and subdirectories. Since the code reads BasicFileAttributes for each path and prints them without error, option A is correct: all files and directories under the home directory are listed with their attributes.

B is wrong because the lambda at line n1 is syntactically valid - lambdas are permitted to contain try-catch blocks, and the checked IOException is properly caught inside the body, so there is no compilation issue.

C is wrong because it describes the behavior of Files.list() (non-recursive, immediate children only), not Files.walk(). The walk includes every nested subdirectory and file, not just the top-level contents of the home directory.

D is wrong because fName.toAbsolutePath() is a perfectly legal call on a Path object - it returns another Path and requires no checked exception handling, so it compiles cleanly.

Memory tip: Think of the method name literally - Files.walk() walks the whole neighborhood (recursive, includes directories), while Files.list() only looks out your front door (one level, files only). If you see walk, expect everything underneath.

Community Discussion

No community discussion yet for this question.

Full 1Z0-809 Practice