nerdexam
Oracle

1Z0-819 · Question #111

Given the fragment: Path source = Paths.get("/repo/a.txt"); Path destination = Paths.get("/repo/"); // line 1 Files.delete(destination); // line 2 Files.delete(source); // line 3 Assuming the source…

The correct answer is A. A java.nio.file.NoSuchFileException is thrown on line 1. Option A as stated appears to be incorrect - and it's worth understanding why, because the real behavior is what the exam is likely testing. Paths.get("/repo/") on line 1 is a pure string-to-Path factory method; it never accesses the filesystem and cannot throw…

Java I/O API

Question

Given the fragment: Path source = Paths.get("/repo/a.txt"); Path destination = Paths.get("/repo/"); // line 1 Files.delete(destination); // line 2 Files.delete(source); // line 3 Assuming the source file a.txt and the folder /repo exist, what is the result?

Options

  • AA java.nio.file.NoSuchFileException is thrown on line 1.
  • BA java.nio.file.NoSuchFileException is thrown on line 2.
  • CA java.io.IOException occurs and /repo/a.txt is deleted.
  • D/repo is removed.

How the community answered

(18 responses)
  • A
    78% (14)
  • B
    6% (1)
  • C
    6% (1)
  • D
    11% (2)

Explanation

Option A as stated appears to be incorrect - and it's worth understanding why, because the real behavior is what the exam is likely testing.

Paths.get("/repo/") on line 1 is a pure string-to-Path factory method; it never accesses the filesystem and cannot throw NoSuchFileException. The real action happens on line 2: Files.delete(destination) attempts to delete the /repo/ directory, which exists but is non-empty (it contains a.txt). In Java NIO, deleting a non-empty directory throws DirectoryNotEmptyException (a subtype of IOException) - not NoSuchFileException. Execution never reaches line 3, so a.txt is never deleted.

Why the distractors fail:

  • B (NoSuchFileException on line 2) is wrong because /repo/ does exist - the exception would be DirectoryNotEmptyException, not NoSuchFileException.
  • C (IOException + a.txt deleted) is wrong because the exception on line 2 aborts execution before line 3 runs.
  • D (/repo is removed) is wrong because Files.delete() on a non-empty directory always fails.

Memory tip: Paths.get() is a dumb string converter - it never touches disk. Files.delete() is the one that talks to the OS, and it refuses to remove a directory unless it's empty (DirectoryNotEmptyException). Think: "No key, no file, no delete of a full drawer."

Note: The stated correct answer (A) appears to be an error in the answer key. The actual behavior is a DirectoryNotEmptyException thrown on line 2 - none of the provided choices capture this exactly, making this a flawed question.

Topics

#NIO#Files API#Paths#Exception handling

Community Discussion

No community discussion yet for this question.

Full 1Z0-819 Practice