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?
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.
題解
程式第 9 行,會將「/green.txt」移動到「/colors/yellow.txt」,原先的「/colors/yellow.txt」會被覆蓋,而「/green.txt」會被刪除。這裡使用了 StandardCopyOption.ATOMIC_MOVE 這個 CopyOption,會將移動檔案的動作變成是 atomic 的,也就是在這個過程中並不會被其他的執行緒介入(像是搶奪檔案的寫入權限)。
選項 A,寫反了。
選項 B,正確答案。雖然「/colors/yellow.txt」已經存在,也沒使用 StandardCopyOption.REPLACE_EXISTING 這個 CopyOption,但使用 StandardCopyOption.ATOMIC_MOVE 來搬移檔案時,已存在的目標檔案會直接被覆蓋。接著程式執行到第 10 行時,由於「/green.txt」已經被搬移走了,所以會拋出 NoSuchFileException。
選項 C,並不會。
選項 D,如果沒有使用 StandardCopyOption.ATOMIC_MOVE 的話,才會因為「/colors/yellow.txt」已經存在而拋出 FileAlreadyExistsException。
注意 Java 的 API 文件有提到,使用 StandardCopyOption.ATOMIC_MOVE 時,如果目標檔案已經存在,是要覆蓋它還是拋出 IOException 是由實作來決定的,並不保證每個平台的行為都一樣。筆者在 Linux 作業系統中的 EXT4 檔案系統執行這段程式時,StandardCopyOption.ATOMIC_MOVE 這個 CopyOption 會強制覆蓋已存在的檔案,因此不會拋出 FileAlreadyExistsException。當程式執行到第 10 行時會拋出 NoSuchFileException,因為來源檔案在搬移之後就會被刪除。
