Question

I have some Hungarian text and I would like it to be encoded with UCS2 encoding

String stringEncoding = "UCS-2";
String contentHardCoded = new String("szigorúan bejelentkezési azonosításhoz".getBytes(),stringEncoding);

But I am getting the following exception

Exception in thread "main" java.io.UnsupportedEncodingException: UCS-2
    at java.lang.StringCoding.decode(StringCoding.java:170)
    at java.lang.String.<init>(String.java:443)
    at java.lang.String.<init>(String.java:515)
    at com.gtl.mindmatics.sms.Main.sendSMS(Main.java:108)
    at com.gtl.mindmatics.sms.Main.main(Main.java:180)
Java Result: 1

What could be wrong?

EDIT

I use the following command to run my jar Actually my command is like

java -Dfile.encoding=UCS-2 -cp MyApp.jar com.sms.Main "9876543210" “UCS-2” > testApp.log

And also what should be the correct encoding that should be used, i used UTF-8 but the output not correct.

Was it helpful?

Solution

You're doing it wrong; a String is a set of characters and that is all. What you do here is:

  • you get the bytes of the string as decoded by your current JVM encoding,
  • you reencode these bytes using a different encoding.

Your string will therefore be completely corrupted. A String does not have an encoding.

See here for more details.


As to UCS-2, it has been superseded by UTF-16. You want to use UTF-16 instead.

Note that you MUST specify the endianness, which matters for UTF-16 unlike for UTF-8. Use:

StandardCharsets.UTF_16LE

(or BE for big endian), or, if you still use Java 6 or lower:

Charset.forName("UTF-16LE") // or BE
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top