1Z0-819 · Question #37
Given the code fragment: Path currentFile = Paths.get("/scratch/exam/temp.txt"); Path outputFile = Paths.get("/scratch/exam/new.txt"); Path directory = Paths.get("/scratch/")…
The correct answer is B. The program throws a FileAlreadyExistsException. Files.copy(currentFile, outputFile) is invoked without StandardCopyOption.REPLACE_EXISTING, which is the flag required to overwrite an existing target file. When the target already exists at the time of the copy, the JVM throws FileAlreadyExistsException immediately - execution…
Question
Options
- AThe /scratch/exam/new.txt and /scratch/new.txt are deleted.
- BThe program throws a FileAlreadyExistsException.
- CThe /scratch/exam/new.txt is deleted.
- DA copy of /scratch/exam/new.txt exists in the /scratch direc ory and /scratch/exam/new.txt is deleted.
How the community answered
(37 responses)- A5% (2)
- B81% (30)
- C11% (4)
- D3% (1)
Explanation
Files.copy(currentFile, outputFile) is invoked without StandardCopyOption.REPLACE_EXISTING, which is the flag required to overwrite an existing target file. When the target already exists at the time of the copy, the JVM throws FileAlreadyExistsException immediately - execution stops on that line, so neither Files.delete call ever runs.
- A is wrong because no deletion occurs at all; the exception thrown during the copy prevents all subsequent statements from executing.
- C is wrong for the same reason:
Files.delete(outputFile)never runs because the exception fires before it. - D is wrong on two counts:
Files.copy(source, target)copies to the exact path given, not into a directory, and the exception again prevents any output anyway.
Memory tip: "Copy needs explicit permission to overwrite." Without REPLACE_EXISTING, Files.copy treats any existing target as an error - you must pass StandardCopyOption.REPLACE_EXISTING as a third argument to allow it.
Topics
Community Discussion
No community discussion yet for this question.