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:

10-Dec-2014 – Executed successfully

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」,才能成功複製檔案。