Java NIOで高速ファイルコピー例

2012/01/04 16:41Update
TAGS: NIO | Java | ファイル | コピー

Java NIOを使った高速ファイルコピー例です。

public static void copyFile(File in, File out) throws IOException {
    FileChannel inChannel = new FileInputStream( in ).getChannel();
    FileChannel outChannel = new FileOutputStream( out ).getChannel(); 
    try { 
        // inChannel.transferTo(0, inChannel.size(), outChannel);
        // Windows 上で大サイズファイルのコピーは問題があるようで、
        // 最大サイズ: 64Mb - 32Kbにします
        int maxCount = (64 * 1024 * 1024) - (32 * 1024); 
        long size = inChannel.size();    //INファイルサイズ
        long position = 0;
        while ( position < size ) {
            //コピー
            position += inChannel.transferTo( position, maxCount, outChannel ); 
        } 
    } finally { 
        if ( inChannel != null ) { 
            inChannel.close(); 
        } 
        if ( outChannel != null ){ 
            outChannel.close(); 
        } 
    } 
}

.

有关作者
Syboos.jp編集長AJavaやオープンソース情報の執筆、Webサイトの開発や運営全般の業務に携わる。

Sponsored Link


Comments

用户名 (required)

Email (will not be published) (required)

URL

Evaluation