Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Loading a Java Charset manually

I'm doing some work using the JavaMail API, and I've run across encodings which Java doesn't support natively (by design), such as UTF7/unicode-1-1-utf-7. For that encoding in particular I found the JUTF7 implementation of a Java Charset and CharsetProvider for UTF7. However, having added the jutf7.jar to my classpath I still get UnsupportedEncodingExceptions, and unicode-1-1-utf-7 is definitely one of JUTF7's aliases.

Is there a way to manually load the Charset or ensure that the Charset is being loaded so that I can rule that out as a cause?

like image 278
Keeblebrox Avatar asked Jun 10 '11 15:06

Keeblebrox


People also ask

What is the default charset for Java?

The native character encoding of the Java programming language is UTF-16. A charset in the Java platform therefore defines a mapping between sequences of sixteen-bit UTF-16 code units (that is, sequences of chars) and sequences of bytes.

How do I save a Java file as UTF-8?

In Java, the OutputStreamWriter accepts a charset to encode the character streams into byte streams. We can pass a StandardCharsets. UTF_8 into the OutputStreamWriter constructor to write data to a UTF-8 file.

What is a Java charset?

Java Character Set | Characters are the smallest units (elements) of Java language that are used to write Java tokens. These characters are defined by the Unicode character set. A character set in Java is a set of alphabets, letters, and some special characters that are valid in java programming language.


2 Answers

There's a bit more to using a new Charset, apart from putting the necessary classes into the classpath. To quote the Javadocs:

A charset provider identifies itself with a provider-configuration file named java.nio.charset.spi.CharsetProvider in the resource directory META-INF/services. The file should contain a list of fully-qualified concrete charset-provider class names, one per line. [...]

( http://download.oracle.com/javase/6/docs/api/java/nio/charset/spi/CharsetProvider.html )

Is this special file present in the JAR?

like image 71
sleske Avatar answered Oct 16 '22 03:10

sleske


You should make sure the jar is loaded by the main classloader. You can achieve this by adding the jar to the JVM's jre/lib/ext extension directory, or by adding it to the classpath of the main program. For example if you are using Tomcat, add -cp /path/to/jutf7.jar to Tomcat's startup script.

Similarly, if you want to test jutf7 from the scala REPL, you need to start it as follows

env JAVA_OPTS="-cp /path/to/jutf7-1.0.0.jar" scala

Tested with Java HotSpot(TM) 64-Bit Server VM (build 20.8-b03-424, mixed mode)

like image 26
Erik van Oosten Avatar answered Oct 16 '22 04:10

Erik van Oosten