バイト列から文字へのエンコード
バイト列から文字へのエンコードはInputStreamReaderなどでできますが、直接エンコードしたいときもあります。そのときはCharsetDecoderを使用します。
例を以下に示します。
/* * This code is under public domain. */ public class DecodeTest { public static int getchar(InputStream ins, Charset encoding) throws IOException { CharsetDecoder cd = encoding.newDecoder(); ByteBuffer bb = ByteBuffer.allocate(8); CharBuffer cb = CharBuffer.allocate(8); byte[] a = new byte[8]; int b; for(int i = 0; i < a.length; i++) { if((b = ins.read()) < 0) { return -1; } a[i] = (byte)b; bb.put(a, 0, i + 1).flip(); if(cd.decode(bb, cb, true).isUnderflow()) { cd.flush(cb); if(cb.flip().hasRemaining()) { return cb.get(); } } else { bb.clear(); } } return -1; } }
« Schluessel Ver. 0.4.3をリリースしました | トップページ | 文字コード自動判別 »
「Java」カテゴリの記事
- 文字コード自動判別(2013.05.04)
- バイト列から文字へのエンコード(2013.05.04)
- 10進浮動小数点(Decimal64, 32)クラスを作成しました(2011.11.06)
- JSONパーサを作成しました(2011.08.21)
- 開平法(2011.06.19)
この記事へのコメントは終了しました。
コメント