カテゴリー
SugiBlog Webエンジニアのためのお役立ちTips

New I/Oの高速ファイル入出力

この記事は最終更新日から1年以上経過しています。

FileクラスにはCopyなどというメソッドがないようなので、調べていたらNew I/Oというものを発見したのでメモ。

java.nio.channels.FileChannelを使用して、簡単にコピーできます。

1File inputFile  = new File("入力元ファイルのパス");
2File outputFile = new File("出力先ファイルのパス");
3 
4try {
5    FileChannel inputChannel  = new FileInputStream(inputFile).getChannel();
6    FileChannel outputChannel = new FileOutputStream(outputFile).getChannel();
7 
8    // インプットチャネルの出力をアウトプットチャネルに接続
9    inputChannel.transferTo(0, inputChannel.size(), outputChannel);
10 
11    inputChannel.close();
12    outputChannel.close();
13} catch (FileNotFoundException e) {
14    e.printStackTrace();
15} catch (IOException e) {
16    e.printStackTrace();
17}
この記事がお役に立ちましたらシェアお願いします
2,838 views

コメントを残す

メールアドレスが公開されることはありません。 が付いている欄は必須項目です