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-catchやthrowsが必要となりますが、文字コードを動的に変更するのでなければ、まず発生し得ない例外なので、記述が冗長になります。
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が不正であれば例外が発生しますが、その場合の例外は全て非検査例外のため、ハンドリング処理が不要になります。