「FileChannel」から「ByteBuffer」に読み込んだバイトを「CharsetDecoder」でchar型にデコードします。
ByteBufferに読み込んだバイトを文字型に変換する処理は、CharsetDecoderで行います。シフトJIS形式のテキストファイルから文字列を読み込んだ場合、2バイト文字の1バイトを読み込んだ時点で、ByteBufferの容量に達してしまう場合があります。その場合、CharsetDecoderのdecode()メソッドの戻り値、CoderResultのisMalformed()がtrueを返しますので、読み込んだバイト数+1のサイズを持つバッファにもう一度読み直しを行ってデコードを行います。
import java.io.FileInputStream;
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.CoderResult;
public class DecodeChar {
public static void main(String[] args) {
System.out.println("--処理開始--");
if(args.length == 0)
{
System.out.println("コマンドライン引数を指定してください");
return;
}
FileChannel inChannel = null;
Charset charset = Charset.forName("Shift_JIS");
CharsetDecoder decoder = charset.newDecoder();
StringBuffer sb = new StringBuffer();
try
{
FileInputStream in = new FileInputStream(args[0]);
inChannel = in.getChannel();
ByteBuffer evenBuff = ByteBuffer.allocateDirect(1024);
CharBuffer evenCBuff = CharBuffer.allocate(1024);
ByteBuffer oddBuff = ByteBuffer.allocateDirect(1025);
CharBuffer oddCBuff = CharBuffer.allocate(1025);
long position = 0;
while(inChannel.read(evenBuff,position) != -1)
{
evenBuff.flip();
CoderResult result = decoder.decode(evenBuff, evenCBuff, true);
if(result.isMalformed())
{
inChannel.read(oddBuff,position);
oddBuff.flip();
decoder.decode(oddBuff, oddCBuff, true);
oddCBuff.flip();
sb.append(oddCBuff.toString());
position += oddBuff.capacity();
oddBuff.clear();
oddCBuff.clear();
}
else
{
evenCBuff.flip();
sb.append(evenCBuff.toString());
position += evenBuff.capacity();
}
evenBuff.clear();
evenCBuff.clear();
}
System.out.println(sb.toString());
}
catch(IOException e)
{
System.out.println(e);
}
finally
{
if(inChannel != null)
{
try
{
inChannel.close();
}catch(Exception e){ System.out.println(e); }
}
}
System.out.println("--処理終了--");
}
}
ちょっと一休み. Javaキーワード並び替えゲーム
画面に表示される文字列を並び替えるとJavaに関連するキーワードになります。ヒントをたよりに並び替えを行ってエンターを押してください。
ユーザ登録をしてログインするとランキングに参加できます。