Javaでファイルをコピーする方法
1. 概要
この記事では、Javaでファイルをコピーする一般的な方法について説明します。
まず、標準のIOとNIO.2 API、および2つの外部ライブラリcommons-ioとguavaを使用します。
2. IO API(JDK7より前)
まず第一に、tocopy a file with java.io API, we’re required to open a stream, loop through the content and write it out to another stream:
@Test
public void givenIoAPI_whenCopied_thenCopyExistsWithSameContents()
throws IOException {
File copied = new File("src/test/resources/copiedWithIo.txt");
try (
InputStream in = new BufferedInputStream(
new FileInputStream(original));
OutputStream out = new BufferedOutputStream(
new FileOutputStream(copied))) {
byte[] buffer = new byte[1024];
int lengthRead;
while ((lengthRead = in.read(buffer)) > 0) {
out.write(buffer, 0, lengthRead);
out.flush();
}
}
assertThat(copied).exists();
assertThat(Files.readAllLines(original.toPath())
.equals(Files.readAllLines(copied.toPath())));
}
このような基本的な機能を実装するには、かなりの労力が必要です。
幸いなことに、Java has improved its core APIs and we have a simpler way of copying files using NIO.2 APIです。
3. NIO.2 API(JDK7)
NIO.2は低レベルのシステムエントリポイントを利用するため、NIO.2を使用するとファイルコピーのパフォーマンスを大幅に向上させることができます。
Files。copy()メソッドがどのように機能するかを詳しく見てみましょう。
copy()メソッドを使用すると、コピーオプションを表すオプションの引数を指定できます。 By default, copying files and directories won’t overwrite existing ones, nor will it copy file attributes.
この動作は、次のコピーオプションを使用して変更できます。
-
REPLACE_EXISTING –は、ファイルが存在する場合はそれを置き換えます
-
COPY_ATTRIBUTES –はメタデータを新しいファイルにコピーします
-
NOFOLLOW_LINKS –はシンボリックリンクをたどるべきではありません
NIO.2 Filesクラスは、ファイルシステム内のファイルとディレクトリをコピーするためのオーバーロードされたcopy()メソッドのセットを提供します。
2つのPath引数を持つcopy()を使用した例を見てみましょう。
@Test
public void givenNIO2_whenCopied_thenCopyExistsWithSameContents()
throws IOException {
Path copied = Paths.get("src/test/resources/copiedWithNio.txt");
Path originalPath = original.toPath();
Files.copy(originalPath, copied, StandardCopyOption.REPLACE_EXISTING);
assertThat(copied).exists();
assertThat(Files.readAllLines(originalPath)
.equals(Files.readAllLines(copied)));
}
directory copies are shallowは、ディレクトリ内のファイルとサブディレクトリがコピーされないことを意味することに注意してください。
4. Apache Commons IO
Javaでファイルをコピーするもう1つの一般的な方法は、commons-ioライブラリを使用することです。
まず、依存関係を追加する必要があります。
commons-io
commons-io
2.6
最新バージョンはMaven Centralからダウンロードできます。
次に、ファイルをコピーするには、copyFile() method defined in the FileUtils class.を使用する必要があります。このメソッドは、ソースファイルとターゲットファイルを取得します。
copyFile()メソッドを使用したJUnitテストを見てみましょう。
@Test
public void givenCommonsIoAPI_whenCopied_thenCopyExistsWithSameContents()
throws IOException {
File copied = new File(
"src/test/resources/copiedWithApacheCommons.txt");
FileUtils.copyFile(original, copied);
assertThat(copied).exists();
assertThat(Files.readAllLines(original.toPath())
.equals(Files.readAllLines(copied.toPath())));
}
5. グアバ
最後に、GoogleのGuavaライブラリを見てみましょう。
繰り返しますが、Guava,を使用する場合は、依存関係を含める必要があります。
com.google.guava
guava
23.0
最新バージョンはon Maven Centralで見つけることができます。
そして、ファイルをコピーするGuavaの方法は次のとおりです。
@Test
public void givenGuava_whenCopied_thenCopyExistsWithSameContents()
throws IOException {
File copied = new File("src/test/resources/copiedWithGuava.txt");
com.google.common.io.Files.copy(original, copied);
assertThat(copied).exists();
assertThat(Files.readAllLines(original.toPath())
.equals(Files.readAllLines(copied.toPath())));
}
6. 結論
この記事では、Javaでファイルをコピーする最も一般的な方法を検討しました。
この記事の完全な実装はover on Github.で見つけることができます