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);