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
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)- A4% (2)
- B2% (1)
- C12% (6)
- D82% (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 -/datais treated as the literal target path, not a directory to copy into (that'scp-style behavior, not Java NIO). - B is wrong because an exception is definitely thrown; the program does not complete normally.
- C is wrong because
FileNotFoundExceptionis not part of the NIO2 API - NIO2 throwsNoSuchFileExceptionwhen a path doesn't exist, notFileNotFoundException(that's from the olderjava.ioAPI).
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.