[Java] Solving the case of IllegalCharsetNameException: «UTF-8»

Have you specified file.encoding as a parameter to the JVM, but ended up getting an unexpected startup exception instead? Here is what caused it and how to fix it.

First the quick important facts for the googlers out there. The solution to your problem is simply to remove the quotation marks from the «UTF-8» string you are passing as the value of the file.encoding parameter to the JVM.

Now, why does that work, and why does it work with the quotation marks in the shell? The reason is simply that if you run your program from the shell, it removes the quotes before handing it over to the jvm. So when you are running
java -Dfile.encoding="UTF-8" MainClass you are really running
java -Dfile.encoding=UTF-8 MainClass.
Whereas when you are specifying this in a configuration file, as Glassfish does for example, these quotes will be part of the string used as the value of the parameter.

The actual reason why it fails with an exception can be found in the source code for CharSet. There you will se that the checkName() method throws an error if the charset name contains any other characters than [a-zA-Z0-9-.]. As quote («) is not in that range, the exception is thrown.

Error occurred during initialization of VM
java.nio.charset.IllegalCharsetNameException: "UTF-8"
at java.nio.charset.Charset.checkName(Charset.java:284)
at java.nio.charset.Charset.lookup2(Charset.java:458)
at java.nio.charset.Charset.lookup(Charset.java:437)
at java.nio.charset.Charset.defaultCharset(Charset.java:579)
at sun.nio.cs.StreamEncoder.forOutputStreamWriter(StreamEncoder.java:37)
at java.io.OutputStreamWriter.(OutputStreamWriter.java:94)
at java.io.PrintStream.(PrintStream.java:100)
at java.lang.System.initializeSystemClass(System.java:1083)

This error can be seen in many different cases, such as configuring Grails, Glassfish, and many others where configuration files are being used to set jvm parameters.

Ett svar til [Java] Solving the case of IllegalCharsetNameException: «UTF-8»

  1. Vincent sier:

    Thaank you!

Legg igjen en kommentar

Fyll inn i feltene under, eller klikk på et ikon for å logge inn:

WordPress.com-logo

Du kommenterer med bruk av din WordPress.com konto. Logg ut / Endre )

Twitter picture

Du kommenterer med bruk av din Twitter konto. Logg ut / Endre )

Facebookbilde

Du kommenterer med bruk av din Facebook konto. Logg ut / Endre )

Google+ photo

Du kommenterer med bruk av din Google+ konto. Logg ut / Endre )

Kobler til %s

%d bloggers like this: