LoginSignup
1
0

More than 5 years have passed since last update.

String.getBytes()のencodeを自作

Last updated at Posted at 2018-05-29

String.getBytes()のencodeを自作

  • 対抗先のシステムの文字コードがSJISでユニコードのコードポイントで文字化けが発生する文字も送付する必要があった。
  • replaceする2度手間より、エンコード時に置換してしまうほうが早いと判断。
private static final Map<Character, byte[]>  conversionCharsetMap = new LinkedHashMap<Character, byte[]>(){
    {
        put('~', new byte[]{(byte) 0x81, (byte) 0x60});
        put('-', new byte[]{(byte) 0x81, (byte) 0x7C});
        put('¢', new byte[]{(byte) 0x81, (byte) 0x91});
        put('£', new byte[]{(byte) 0x81, (byte) 0x92});
        put('¬', new byte[]{(byte) 0x81, (byte) 0xCA});
        put('―', new byte[]{(byte) 0x81, (byte) 0x5C});
        put('∥', new byte[]{(byte) 0x81, (byte) 0x61});
    }
 };

public byte[] encode(String str, String charsetName){

    Charset charset = Charset.forName(charsetName);

    CharsetEncoder encoder = charset.newEncoder();

    CharBuffer inBuf = CharBuffer.wrap(str);

    ByteBuffer outBuf = ByteBuffer.allocate(inBuf.length() * (int)encoder.maxBytesPerChar());

    CoderResult result;

    // CoderResultがエラーを返す間ループ
    while((result = encoder.encode(inBuf, outBuf, true)).isError()) {

        // リセット
        encoder.reset();

        // マッピング不可なら
        // 例えばTF-8⇒SJIS(MS932ではない)で失敗する文字~∥-¢£¬―などここに入る
        if(result.isUnmappable()) {

            // 1文字取得(マッピングに失敗した文字)
            char ch = inBuf.get();
            byte[] val = null;

            // この辺にマッピングに失敗したらどうするかの処理を入れる
            // ここではマッピングに失敗した文字のSJIS用のバイトコードをマップから取得している      
            val = conversionCharsetMap.get(ch);


            // エンコード結果用バイトバッファにプット
            outBuf.put(val);
        }
        // 不正入力
        if(result.isMalformed()) {
            // これは基本的にはほとんどない。
        }
    }

    // エンコード結果バッファにフラッシュ
    encoder.flush(outBuf);

    // バッファをフリップ(反転)開始位置に戻す
    outBuf.flip();

    return Arrays.copyOf(outBuf.array(), outBuf.limit());
}
1
0
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0