# 搬移檔案 move
```java=
public class Test {
public static void main(String[] args) {
Path source = Paths.get("C:\\Users\\A7024\\git-sideProject\\exam.ocpjp\\green.txt");
Path target = Paths.get("C:\\Users\\A7024\\git-sideProject\\exam.ocpjp\\colors\\yellow.txt");
try {
Files.move(source, target, StandardCopyOption.ATOMIC_MOVE);
Files.delete(source);
} catch (IOException e) {
e.printStackTrace();
}
}
}
```
Console:
```=
java.nio.file.NoSuchFileException: C:\Users\A7024\git-sideProject\exam.ocpjp\green.txt
at sun.nio.fs.WindowsException.translateToIOException(WindowsException.java:79)
at sun.nio.fs.WindowsException.rethrowAsIOException(WindowsException.java:97)
at sun.nio.fs.WindowsException.rethrowAsIOException(WindowsException.java:102)
at sun.nio.fs.WindowsFileSystemProvider.implDelete(WindowsFileSystemProvider.java:269)
at sun.nio.fs.AbstractFileSystemProvider.delete(AbstractFileSystemProvider.java:103)
at java.nio.file.Files.delete(Files.java:1126)
at exam.ocpjp.v1.q089.Test.main(Test.java:16)
```
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.
- [x] **Answer: B**
:::info
程式第6行,會將「/green.txt」移動到「/colors/yellow.txt」,原先的「/colors/yellow.txt」會被覆蓋,而「/green.txt」會被刪除。這裡使用了StandardCopyOption.ATOMIC_MOVE這個CopyOption,會將移動檔案的動作變成是atomic的,也就是在這個過程中並不會被其他的執行緒介入(像是搶奪檔案的寫入權限),。
所以green.txt 裡面的內容 會被複製到 yellow.txt裡面
然後green.txt會被刪除
:::
###### tags: `ocpjp`