Javaの文字コード変換サンプルコード2
java.nio.charset.Charsetにあるdecodeとencodeの挙動が気になったのでサンプルを書いてみた。 まず、仕様の簡単な説明。 Charset.encodeは、入力としてStringを受け取り、出力として任意の文字コードのバイト列を出力する。 Charset.decodeは、入力として、UTF-8とかShift-JISでエンコードされた文字のバイト列を与えると、出力としてUnicode(UTF-16)で変換された文字のバイト列が出力される。 文字コードの指定は下記のようにCharsetのインスタンスを取得する過程で行う。 Charset cs = Charset.forName("Shift-JIS") cs.encode(new String("エンコードしたい文字")); 次に、サンプルコードを書いて、encode/decodeした時にどのようなバイト列が格納されているのか確認してみた。 public static void sampleEncoder(String target,Charset cs){ /** まずは元のStringデータをCharに分解して確認してみる**/ System.out.print("Original: "); char[] chars = new char[target.length()]; target.getChars(0,target.length(),chars,0); for(int i = 0; i < chars.length; i++){ System.out.print((int)chars[i] + " "); } System.out.println(); /** 次にStringを指定されたEncodeに変換し、バイト表現を確認する **/ ByteBuffer bf = cs.encode(target); System.out.print(cs.toString() + ": "); for(int i = 0 ; i < bf.array().length; i++) { Sy...