Mutant World

Monday, January 01, 2007

UTF-8 handling for ResourceBundle and Properties

Every new version of the JDK comes with small improvements, often unnoticed, that however correct long-standing bugs or request for enhancements.

One such improvements is - finally! - the ability for java.util.Properties to handle non ISO-8859-1 properties files.
At first seems like a very small improvement, but anyone that worked on localizing an application (for example translating messages into a country specific language) knows that encoding problems are just painful, and that is far too easy to waste days trying to get them right.

JDK 5 added a new API, namely Properties.loadFromXML(InputStream), that allowed to specify properties using an XML syntax, and hence to specify the encoding of the XML file in the XML declaration (the first line of an XML file):

<?xml version="1.0" encoding="UTF-8" ?>
<properties>
<entry key="hello.world">Καλημέρα κόσμε</entry>
</properties>

JDK 6 went further, adding Properties.load(Reader): in case the encoding is known a priori by the program, it is possible to create a Reader that uses the specific encoding to read the properties file.

However, in JDK 5, java.util.ResourceBundle was only able to read properties files that were encoded in ISO-8859-1, and this forced the translators to put horrible unicode escapes instead of real text. Following the above example, in JDK 5 you have to write the properties file containing translations like this:

hello.world=\u039A\u03B1\u03BB\u03B7\u03BC\u03AD\u03C1\u03B1 \u03BA\u03CC\u03C3\u03BC\u03B5

Pretty ugly, especially when you think that the API to read properties file in XML format is already present in JDK 5, only that ResourceBundle has not been updated to use it.

Fortunately, with JDK 6 it is possible to solve this problem, although requires a bit of coding (see below).

In JDK 6 ResourceBundle has been extended to give the user more control on how to load resources, by subclassing java


 

Follow Lee on X/Twitter - Father, Husband, Serial builder creating AI, crypto, games & web tools. We are friends :) AI Will Come To Life!

Check out: eBank.nz (Art Generator) | Netwrck.com (AI Tools) | Text-Generator.io (AI API) | BitBank.nz (Crypto AI) | ReadingTime (Kids Reading) | RewordGame | BigMultiplayerChess | WebFiddle | How.nz | Helix AI Assistant