0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Javaで文字列⇔バイト配列の変換を行う際は、Charset.forName使った方がいい

Last updated at Posted at 2025-04-13

Javaで文字列⇔バイト配列の変換を行う際に、検査例外のUnsupportedEncodingExceptionの対応として、基本的例外発生しないのにtry-catchかかないといけなくなる。

それを防ぐ書き方がある。
Charset.forNameを使うのがよい

文字コードの指定にCharset型を使用すると、UnsupportedEncodingExceptionが発生しなくなる

例)

	String str = "テスト";

    // UTF-8
	byte[] utf8Bytes = str.getBytes(StandardCharsets.UTF_8);

    // windows-31j(MS932)
	byte[] sjisBytes = str.getBytes(Charset.forName("windows-31j"));
0
0
0

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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?