解答例 - 実習課題2 - 3.ファイルチャネル
(実習課題2)
実習課題1のプログラムを変更し、ファイルの読み込みでMappedByteBufferを使用するようにしてください。
解答例
public class Main {
private static final String IN_FILE = "in.dat";
private static final String OUT_FILE = "out.dat";
public static void main(String[] args) {
Main buff = new Main();
String inFile = IN_FILE;
String outFile = OUT_FILE;
long start = System.currentTimeMillis();
buff.turnBit(inFile, outFile);
long end = System.currentTimeMillis();
System.out.print("経過時間:");
System.out.println((end - start) + "msec\t");
}
private void turnBit(String inFile, String outFile) {
try {
FileInputStream input = new FileInputStream(inFile);
FileOutputStream output = new FileOutputStream(outFile);
FileChannel inCh = input.getChannel();
FileChannel outCh = output.getChannel();
long size = 0;
size = inCh.size();
MappedByteBuffer buffer = null;
try {
// MappedByteBufferを使用してバッファ生成
buffer = inCh.map(FileChannel.MapMode.READ_ONLY, 0, size);
} catch (IOException e1) {
e1.printStackTrace();
} catch (Throwable e) {
e.printStackTrace();
}
inCh.read(buffer);
// 内容を反転する
byte[] bytes = turnBit(buffer);
outCh.write(ByteBuffer.wrap(bytes));
outCh.force(false);
input.close();
output.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
private byte[] turnBit(ByteBuffer buffer) {
int len = 8 * buffer.capacity();
// ビット配列を生成する
BitArray array = new BitArray(len);
byte[] bytes = buffer.array();
int x = 0;
for (int i = 0; i < bytes.length; i++) {
for (int j = 0; j < 8; j++) {
if (x > len)
break;
int mask = 1 << j;
boolean value = (mask & bytes[i]) != 0;
array.set(x, value);
x++;
}
}
// 反転
for (int i = 0; i < len; i++) {
boolean bit = array.get(i);
array.set(i, !bit);
}
return array.toByteArray();
}
}

