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,因此會在移動檔案之前拋出FileAlreadyExistsException。檔案並不會被移動。

選項C,並不會。

選項D,會拋出FileAlreadyExistsException,原因見選項B。

注意這邊的程式實際執行時可能會有一些問題,算是Java的BUG。筆者在Linux作業系統上中的EXT4檔案系統執行這段程式時,StandardCopyOption.ATOMIC_MOVE這個CopyOption會強制覆蓋已存在的檔案,因此不會拋出FileAlreadyExistsException。當程式執行到第10行時會拋出NoSuchFileException,因為來源檔案在搬移之後就會被刪除。