java.io.UnsupportedEncodingException: UTF String.getBytes

The java String.getBytes method converts the specified string to bytes in the encoding format. If the java does not support the encoding format, the method String.getBytes throws java.io.UnsupportedEncodingException with the encoding format provided.

Exception in thread "main" java.io.UnsupportedEncodingException: UTF
	at java.lang.StringCoding.encode(StringCoding.java:341)
	at java.lang.String.getBytes(String.java:918)
	at com.yawintutor.StringGetBytes.main(StringGetBytes.java:8)


Root Cause

The given encoding format name in the String.getBytes method is incorrect or not supported by the java. The supported encoding formats are available in https://docs.oracle.com/javase/8/docs/technotes/guides/intl/encoding.doc.html



How to reproduce this issue

The example below will throw java.io.UnsupportedEncodingException. The encoding scheme “UTF” is a invalid encoding scheme name.

package com.yawintutor;
 

 public class StringGetBytes {
 public static void main(String[] args) throws Exception {
 String str = "Bangalore";
 byte[] bytes;
 

 bytes = str.getBytes("UTF");
 

 System.out.println("Given  String : " + str);
 System.out.println("Output bytes   : " + bytes);
 }
 }
 


Solution

The java supported encoding scheme name should be provided in String.getBytes method. The list of java supported methods are available in https://docs.oracle.com/javase/8/docs/technotes/guides/intl/encoding.doc.html. The CharsetEncoder class should be used when more control over the encoding process is required. The String.getBytes method returns with array of bytes

package com.yawintutor;

public class StringGetBytes {
	public static void main(String[] args) throws Exception {
		String str = "Bangalore";
		byte[] bytes;

		bytes = str.getBytes("UTF-16");

		System.out.println("Given  String : " + str);
		System.out.println("Output bytes   : " + bytes);
	}
}

Output

Given  String : Bangalore
Output bytes   : [B@7852e922



Related Articles

Leave a Reply

Your email address will not be published. Required fields are marked *