Given the code fragment:
Path source = Paths.get("/data/december/log.txt");
Path destination = Paths.get("/data");
Files.copy(source, destination);
and assuming that the file /data/december/log.txt is accessible and contains:
What is the result?
A. A file with the name log.txt is created in the /data directory and the content of the /data/december/log.txt file is copied to it.
B. The program executes successfully and does NOT change the file system.
C. A FileNotFoundException is thrown at run time.
D. A FileAlreadyExistsException is thrown at run time.
题解
若 /data 已存在,程序会抛出 FileAlreadyExistsException。若 /data 不存在,会在「/」目录下产生「data」文件,内容为「10-Dec-2014 – Executed successfully」。
所以这题选择选项 D 的话会比较合适。
若要避免 FileAlreadyExistsException,可以在 Files 类别的 copy 方法加入 CopyOption 至第三个参数中,如下:
Files.copy(source, destination, StandardCopyOption.REPLACE_EXISTING);
不过在这题的情况下,「/data」目录里面还有「december」目录,并不是空的目录,就算加入了 StandardCopyOption.REPLACE_EXISTING,也会改成抛出 DirectoryNotEmptyException。要把 destination 改成「/data/log.txt」,才能成功拷贝文件。
