概要
Javaで「ファイルやディレクトリをコピーする(Files.copy)」の動作を確認してみました。以下のページを参考にしました。
実装
以下のファイルを作成しました。
JSample11_1.java
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.Files;
import java.io.IOException;
class JSample11_1{
public static void main(String[] args){
Path p1 = Paths.get("/code/java/file/doc/memo.txt");
Path p2 = Paths.get("/code/java/file/doc/memo.back");
Path p3 = Paths.get("/code/java/file/doc/src");
Path p4 = Paths.get("/code/java/file/doc/dest");
try{
Files.copy(p1, p2);
Files.copy(p3, p4);
}catch(IOException e){
System.out.println(e);
}
}
}
以下のコマンドを実行しました。
$ javac JSample11_1.java
$ java JSample11_1
$ cd /code/java/file/doc/
$ ls
dest manual memo.back memo.txt src
以下のファイルを作成しました。
JSample11_2.java
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.Files;
import java.io.IOException;
import static java.nio.file.StandardCopyOption.REPLACE_EXISTING;
class JSample11_2{
public static void main(String[] args){
Path p1 = Paths.get("/code/java/file/doc/memo.txt");
Path p2 = Paths.get("/code/java/file/doc/memo.back");
try{
Files.copy(p1, p2, REPLACE_EXISTING);
}catch(IOException e){
System.out.println(e);
}
}
}
以下のコマンドを実行しました。
$ javac JSample11_2.java
$ java JSample11_2
$ ll /code/java/file/doc/
合計 28
drwxrwxr-x 5 ******** ******** 4096 8月 13 08:20 ./
drwxr-xr-x 3 ******** ******** 4096 8月 11 07:52 ../
drwxrwxr-x 2 ******** ******** 4096 8月 13 08:17 dest/
drwxrwxr-x 2 ******** ******** 4096 8月 11 07:55 manual/
-rw-rw-r-- 1 ******** ******** 21 8月 13 08:20 memo.back
-rw-rw-r-- 1 ******** ******** 21 8月 13 08:16 memo.txt
drwxrwxr-x 2 ******** ******** 4096 8月 13 08:16 src/
まとめ
何かの役に立てばと。