2015年10月25日日曜日

文字列とバイト列間のencode, decodeメモ

CharsetEncoderとCharsetDecoderを使った、文字列とバイト列の変換。

・Stringからbyte[]に変換
変換できない文字があった場合、例外通知するようにCodingErrorAction.REPORTを設定した例。
    Stirng src = "aaaa";
    CharsetEncoder encoder = Charset.forName("UTF-8").newEncoder()
            .onMalformedInput(CodingErrorAction.REPORT)
            .onUnmappableCharacter(CodingErrorAction.REPORT);
    CharBuffer cb = CharBuffer.wrap(src);
    buf = encoder.encode(cb);
    byte[] array = buf.array()
または、使い方によっては、こちら。
    Stirng src = "aaaa";
    CharsetEncoder encoder = Charset.forName("UTF-8").newEncoder()
            .onMalformedInput(CodingErrorAction.REPORT)
            .onUnmappableCharacter(CodingErrorAction.REPORT);
    CharBuffer cb = CharBuffer.wrap(src);
    ByteBuffer mbuf = ByteBuffer.allocate(1000);
    encoder.reset().encode(cb, mbuf, true); //戻り値チェックしたほうがいいかも
    byte[] array = buf.array()
・byte[]からString こっちの場合も、変換できない文字があった場合、例外通知するようにCodingErrorAction.REPORTを設定した例。
    byte[] a = {1, ,2, 3}
    CharsetDecoder decoder = Charset.forName("US-ASCII").newDecoder()
            .onMalformedInput(CodingErrorAction.REPORT)
     .onUnmappableCharacter(CodingErrorAction.REPORT);
    CharBuffer buf = decoder.decode(ByteBuffer.wrap(a));
    String s = buf.toString();
または、使い方によっては、こちら。
    CharsetDecoder decoder = Charset.forName("US-ASCII").newDecoder()
            .onMalformedInput(CodingErrorAction.REPORT)
     .onUnmappableCharacter(CodingErrorAction.REPORT);
    CharBuffer cb = CharBuffer.allocate(1000); 
    decoder.reset().decode(ByteBuffer.wrap(a), cb, true); //戻り値チェックしたほうがいいかも
    String s = cb.flip().toString();