最近のトラックバック

2019年5月
      1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31  
無料ブログはココログ

« Schluessel Ver. 0.4.3をリリースしました | トップページ | 文字コード自動判別 »

バイト列から文字へのエンコード

バイト列から文字へのエンコードは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」カテゴリの記事

コメント

この記事へのコメントは終了しました。

トラックバック


この記事へのトラックバック一覧です: バイト列から文字へのエンコード:

« Schluessel Ver. 0.4.3をリリースしました | トップページ | 文字コード自動判別 »