プログラム悪戦苦闘日記

はてなダイアリーからの移行(遺物)

Java New I/O -part4-

 今回はチャネルのはなし、とはいってもあまり書くことはない。重要なのはread()でByteBufferから読み、write()でByteBufferに書き込むだけだ。逆に言うとBuffer系はByteBufferだけしか使えないのかも。
 
 そんなわけでTechScoreにある第3回の実習課題1でもやってみた。(http://www.techscore.com/tech/Java/NIO/answer/3-1.html

import java.io.*;
import java.nio.*;
import java.nio.channels.*;

/**
 *   以下の仕様を満たすアプリケーションを作成してください。
 *
 *       - ファイルを読み込み、その内容をすべてビット反転した新しいファイルを出力するプログラム。
 *       - 1番目の引数で入力するファイル名を指定すること。
 *       - 2番目の引数で出力するファイル名を指定すること。
 *       - ファイルの入出力にはFileChannelを使用すること。
 *       - 処理にかかった時間をミリ秒単位でコンソールに出力すること。
 */
public class Main {
    public static void main(String[] args) 
    throws Exception {
        if( args.length != 2 )
            return;
            
        final long start = System.nanoTime();
            
        FileInputStream  in    = new FileInputStream(args[0]);
        FileOutputStream out   = new FileOutputStream(args[1]);
        FileChannel      inch  = in.getChannel();
        FileChannel      outch = out.getChannel();
        
        ByteBuffer buf = ByteBuffer.allocate((int) inch.size());
        inch.read(buf);
        buf.flip();
        
        while(buf.position() < buf.limit()) {
            byte b = buf.get();
            buf.position(buf.position() - 1);
            buf.put((byte) (b ^ 0xFF));
        }
        
        buf.flip();
        outch.write(buf);
        
        outch.force(true);
        out.close();
        in.close();
        
        final long end = System.nanoTime();
        final long dt = (end - start) / 1000L;
        
        System.out.println("処理時間:" + dt + "micro sec");
    }
}