JDK1.4から導入された New I/O。
従来より高速に処理ができる。
package nio;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.channels.FileChannel;
import java.nio.charset.Charset;
import java.nio.charset.CharsetDecoder;
import java.nio.charset.CharsetEncoder;
public class NioSample {
public static void main(String[] args) throws IOException {
// input file
FileInputStream stream = new FileInputStream(new File("./hoge"));
FileChannel inch = stream.getChannel();
// output file
File out = new File("./fuga");
out.createNewFile();
FileOutputStream outstream = new FileOutputStream(out);
FileChannel outch = outstream.getChannel();
// bufferの準備
ByteBuffer buf = ByteBuffer.allocateDirect(1000);
// エンコード、デコードの準備
Charset charset = Charset.forName("UTF-8");
CharsetDecoder decoder = charset.newDecoder();
CharsetEncoder encoder = charset.newEncoder();
while(inch.read(buf) > 0) {
buf.flip();
// デコードして読み込み
CharBuffer chb = decoder.decode(buf);
// CharBufferを準備して、このCharBufferで編集
CharBuffer chba = CharBuffer.allocate(1000);
chba.put(chb).put('1').put('2').put("hoge");
chba.flip();
// エンコードして書き込み
outch.write(encoder.encode(chba));
}
// チャンネルのクローズ
inch.close();
outch.close();
}
}