第107回 ファイルチャンネルの入出力
引き続き「ファイルチャンネルの入出力」について見ていきます。
FileChannelはバイトを他のチャネルへ転送することができたり、他のチャネルから転送することができます。
transferFromメソッドは他のチャンネルからバイトを転送します。
transferToメソッドは他のチャンネルにバイトを転送します。
この転送は、チャンネルからバイトを読み込み、ターゲットのチャンネルにそのバイト書き込むよりも効率的に処理できる可能性があります。
次のサンプルコードはファイルからファイルにバイトを転送するプログラムです。
異なる2つのファイルに同じ内容を転送します。
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.nio.channels.FileChannel;
public class Main {
public static void main(String[] strings) {
FileChannel fileChannel = null;
try {
FileInputStream fileInputStream
= new FileInputStream("input.txt");
fileChannel = fileInputStream.getChannel();
transferFromTest(fileChannel);
transferToTest(fileChannel);
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
fileChannel.close();
} catch (Exception e) {}
}
}
public static void transferFromTest(FileChannel inFileChannel)
throws Exception {
FileChannel outFileChannel = null;
try {
FileOutputStream fileOutputStream
= new FileOutputStream("output1.txt");
outFileChannel = fileOutputStream.getChannel();
outFileChannel.transferFrom(inFileChannel, outFileChannel.size(),
inFileChannel.size() - inFileChannel.position());
} finally {
try {
outFileChannel.close();
} catch (Exception e) {}
}
}
public static void transferToTest(FileChannel inFileChannel)
throws Exception {
FileChannel outFileChannel = null;
try {
FileOutputStream fileOutputStream
= new FileOutputStream("output2.txt");
outFileChannel = fileOutputStream.getChannel();
outFileChannel.position(outFileChannel.size());
inFileChannel.transferTo(0, inFileChannel.size()
, outFileChannel);
} finally {
try {
outFileChannel.close();
} catch (Exception e) {}
}
}
}
1つ目のファイルにはtransferFromメソッドでバイトを転送しています。
transferFromメソッドの引数には、転送元のチャンネル、転送先のファイルの開始位置、転送される最大バイト数を指定します。(絶対位置への転送)
今回のように転送元のチャンネルがFileChannelの場合、そのチャンネルの現在位置(position)
からのバイトを転送します。
2つ目のファイルにはtransferToメソッドでバイトを転送しています。
transferToメソッドの引数には、転送元のファイルの開始位置、転送される最大バイト数、転送先のチャンネルを指定します。
今回のように転送先のチャンネルがFileChannelの場合、そのチャンネルの現在位置(position)
に転送を行います。(相対位置への転送)

