nerdexam
Oracle

1Z0-809 · Question #74

Path source = Paths.get("/data/december/log.txt"); Path destination = Paths.get("/data"); Files.copy(source, destination); What is the result?

The correct answer is D. A FileAlreadyExistsException is thrown at run time. Files.copy(source, destination) copies the source to the exact path given as destination - here /data, which already exists as a directory. Since no StandardCopyOption.REPLACE_EXISTING flag is passed, the method throws FileAlreadyExistsException rather than overwrite anything…

Question

Path source = Paths.get("/data/december/log.txt"); Path destination = Paths.get("/data"); Files.copy(source, destination); What is the result?

Options

  • AA file with the name log.txt is created in the /data directory and the content of the /data/december/log.txt file is copied to it.
  • BThe program executes successfully and does NOT change the file system.
  • CA FileNotFoundException is thrown at run time.
  • DA FileAlreadyExistsException is thrown at run time.

How the community answered

(50 responses)
  • A
    4% (2)
  • B
    2% (1)
  • C
    12% (6)
  • D
    82% (41)

Explanation

Files.copy(source, destination) copies the source to the exact path given as destination - here /data, which already exists as a directory. Since no StandardCopyOption.REPLACE_EXISTING flag is passed, the method throws FileAlreadyExistsException rather than overwrite anything at that path.

Why the distractors are wrong:

  • A is wrong because Files.copy() does not append the source filename to the destination - /data is treated as the literal target path, not a directory to copy into (that's cp-style behavior, not Java NIO).
  • B is wrong because an exception is definitely thrown; the program does not complete normally.
  • C is wrong because FileNotFoundException is not part of the NIO2 API - NIO2 throws NoSuchFileException when a path doesn't exist, not FileNotFoundException (that's from the older java.io API).

Memory tip: Remember "NIO2 is strict by default" - Files.copy() will never silently overwrite. If the destination exists (file or directory), you get FileAlreadyExistsException unless you explicitly pass StandardCopyOption.REPLACE_EXISTING.

Community Discussion

No community discussion yet for this question.

Full 1Z0-809 Practice