2011年2月16日水曜日

[Java]ファイルを簡単にコピーする

Javaにはファイルをコピーするメソッドが存在しません。そのためInputStreamとOutputStreamのread/writeで処理しますが、もっと簡単な方法がありました。コードはこんな感じ。

/**
 * ファイルコピーします。
 *
 * @param srcPath コピー元
 * @param destPath コピー先
 */

public static void copy(File srcPath, File destPath) {

    FileChannel srcChannel = null;
    FileChannel destChannel = null;

    try {
        srcChannel = new FileInputStream(srcPath).getChannel();
        destChannel = new FileOutputStream(destPath).getChannel();

        srcChannel.transferTo(0, srcChannel.size(), destChannel);

    } catch (IOException e) {
        e.printStackTrace();

    } finally {
        if (srcChannel != null) {
            try {
                srcChannel.close();
            } catch (IOException e) {
            }
        }
        if (destChannel != null) {
            try {
                destChannel.close();
            } catch (IOException e) {
            }
        }
    }
}

0 件のコメント: