カテゴリー
SugiBlog Webデザイナー・プログラマーのためのお役立ちTips

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

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

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

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

File inputFile  = new File("入力元ファイルのパス");
File outputFile = new File("出力先ファイルのパス");

try {
    FileChannel inputChannel  = new FileInputStream(inputFile).getChannel();
    FileChannel outputChannel = new FileOutputStream(outputFile).getChannel();

    // インプットチャネルの出力をアウトプットチャネルに接続
    inputChannel.transferTo(0, inputChannel.size(), outputChannel);

    inputChannel.close();
    outputChannel.close();
} catch (FileNotFoundException e) {
    e.printStackTrace();
} catch (IOException e) {
    e.printStackTrace();
}
この記事がお役に立ちましたらシェアお願いします
2,700 views

コメントを残す

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