nerdexam
Oracle

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…

Java I/O API

Question

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/"); Files.copy(currentFile, outputFile); Files.delete(outputFile); Files.delete(directory); The /scratch/exam/temp.txt file exists. The /scratch/exam/new.txt and /scratch/new.txt files do not exist. Which statement is true?

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)
  • A
    5% (2)
  • B
    81% (30)
  • C
    11% (4)
  • D
    3% (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

#Files.copy()#Files.delete()#Exception handling#Path API

Community Discussion

No community discussion yet for this question.

Full 1Z0-819 Practice