Avoid UnsupportedEncodingException with Charset.forName

An example of an 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) {
		//It can't happen, but you have to write
	}
}

You can use String.getBytes (String charsetName) or new String (byte [] bytes, String charsetName) when converting a string ⇔ byte array in Java, but charsetName is invalid. In this case, the checked exception ʻUnsupportedEncodingExceptionoccurs. Since it is a checked exception,try-catch and throws` are required, but unless the character code is changed dynamically, it is an exception that can hardly occur, so the description becomes redundant.

Use 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"));
}

If you use the Charset type to specify the character code, ʻUnsupportedEncodingExceptionwill not occur. UTF-8 is provided as a constant in thejava.nio.charset.StandardCharsets class, but since there is no SJIS, use Charset.forName (String charsetName) . Of course, if charsetName` is invalid, an exception will be thrown, but all the exceptions in that case are unchecked exceptions, so handling processing is unnecessary.

Recommended Posts

Avoid UnsupportedEncodingException with Charset.forName