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,因为来源文件在搬移之后就会被删除。
