package jp.gr.java_conf.mrig.io; import java.io.UnsupportedEncodingException; /** * 文字エンコーディングを表すクラス. *

* 例1:
* エンコード名を指定してEncodingオブジェクトを生成する。
*

 * Encoding sjis = Encoding.getEncoding("Shift_JIS");
 * String unicodeString = sjis.getString(shift_jis_string);
 * 
*

*

* 例2:
* 定義済みEncodingオブジェクトを利用する。
*

 * String unicodeString = Encoding.sjis.getString(shift_jis_string);
 * 
* * 上記コードは次と等価になる.
*
 * String unicodeString;
 * try {
 *     unicodeString = new String(shift_jis_string.getByte("iso-8859-1"), "Shift_JIS");
 * } catch (UnsupportedEncodingException e) {
 *     throw new IllegalArgumentException(e.getMessage());
 * }
 * 
*

* */ public class Encoding { // /** Shift_JISを表す定義済みオブジェクト */ // public static final Encoding sjis = getEncoding("Shift_JIS"); // /** EUC_JPを表す定義済みオブジェクト */ // public static final Encoding eucjp = getEncoding("EUC_JP"); /** 文字エンコーディングの文字表現 */ private final String encoding; /** * Encodingオブジェクトを取得する。 * @exception IllegalArgumentException encがサポートされない文字コードの時 */ public static Encoding getEncoding(String enc) { try { //encがサポートされない場合はUnsupportedEncodingExceptionが発生する。 new String(new byte[0], enc); return new Encoding(enc); } catch(UnsupportedEncodingException e) { throw new IllegalArgumentException(e.getMessage()); } } /** * privateコンストラクタ */ private Encoding(String enc) { this.encoding = enc; } /** * Unicode文字列を取得する。 */ public String getString(String s) { if (s == null) return null; try { return new String(getRawBytes(s), this.encoding); } catch(UnsupportedEncodingException e) { //絶対に起こらないはずの例外 e.printStackTrace(); throw new IllegalStateException(e.getMessage()); } } /** * sをiso-8859-1 文字列とみなして、byte配列に変換する。 *

* 誤ってASCIIとして文字列して構築されたStringを元のバイト列に戻す時に利用する。 *

* @param s 変換する文字列 */ public static byte[] getRawBytes(String s) { if (s == null) { return null; } try { return s.getBytes("iso-8859-1"); } catch (UnsupportedEncodingException e) { //絶対に起こらないはずの例外 e.printStackTrace(); throw new IllegalStateException(e.getMessage()); } } }