LoginSignup
9
5

More than 5 years have passed since last update.

Charset.forNameでUnsupportedEncodingExceptionを回避する

Posted at

UnsupportedEncodingExceptionが発生する例

public static void main(String[] args) {
    try {
        String str = "hello";
        byte[] utf8Bytes = str.getBytes("UTF-8");
        byte[] sjisBytes = str.getBytes("SJIS");
    } catch(UnsupportedEncodingException e) {
        // 発生し得ないが、書くしかない
    }
}

Javaで文字列⇔バイト配列の変換を行う際に、String.getBytes(String charsetName)new String(byte[] bytes,String charsetName)を使うことができますが、charsetNameが不正な場合に、検査例外であるUnsupportedEncodingExceptionが発生します。
検査例外のため、try-catchthrowsが必要となりますが、文字コードを動的に変更するのでなければ、まず発生し得ない例外なので、記述が冗長になります。

Charset.forNameを使う

public static void main(String[] args) {
    String str = "hello";
    byte[] utf8Bytes = str.getBytes(StandardCharsets.UTF_8);
    byte[] sjisBytes = str.getBytes(Charset.forName("SJIS"));
}

文字コードの指定にCharset型を使用すると、UnsupportedEncodingExceptionが発生しなくなります。
UTF-8はjava.nio.charset.StandardCharsetsクラスの定数として用意されていますが、SJISは無いので、Charset.forName(String charsetName)を使います。
当然、charsetNameが不正であれば例外が発生しますが、その場合の例外は全て非検査例外のため、ハンドリング処理が不要になります。

9
5
1

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
9
5