1Z0-809 practice question 5 of 25

Given that /green.txt and /colors/yellow.txt are accessible, and the code fragment: Path source = Paths.get(“/green.txt); Path target = Paths.get(“/colors/yellow.txt); Files.move(source, target, StandardCopyOption.ATOMIC_MOVE); Files.delete(source); Which statement is true?

Full set: 196 questions
Answer options
A: The green.txt file content is replaced by the yellow.txt file content and the yellow.txt file is deleted.
B: The yellow.txt file content is replaced by the green.txt file content and an exception is thrown.
C: The file green.txt is moved to the /colors directory.
D: A FileAlreadyExistsException is thrown at runtime. Correct answer
Correct Answer:
D. A FileAlreadyExistsException is thrown at runtime.
Explanation

The Files.move() method attempts to move the source file to the target path. The question states that the target file, /colors/yellow.txt, already exists. When the target file exists and the REPLACEEXISTING copy option is NOT specified, the move operation fails. Consequently, the Java NIO API throws a FileAlreadyExistsException to indicate this condition. The subsequent Files.delete(source) line is never reached because the exception interrupts the normal execution flow.

Why Incorrect

A. No file content is replaced. The move operation fails before any modification can occur because the target file already exists.
B. The move operation fails by throwing an exception immediately upon discovering the existing target file; no content is replaced first.
C. The file is not moved. The operation is aborted due to the pre-existing target file, and an exception is thrown.

References

1. Oracle, "Java SE 8 API Documentation, java.nio.file.Files class, move(Path, Path, CopyOption...) method". The documentation states: "If the target file exists then it is implementation specific if the existing file is replaced or this method fails by throwing an IOException... If the options array contains the REPLACEEXISTING option, then the target file is replaced if it exists." Without this option, the standard behavior is to throw FileAlreadyExistsException.

2. Oracle, "Java SE 8 API Documentation, java.nio.file.FileAlreadyExistsException class". This exception is "Checked exception thrown when an attempt is made to create a file or directory in a location where a file of that name already exists."

Scroll to Top