views:

304

answers:

3

Can I use java.util.Properties with encoding different then default?

+4  A: 

Yes, but then you have to be careful to use the load() and store() methods that take a Reader/Writer, and explicitly construct those by using an InputStreamReader/OutputStreamWriter with the correct encoding.

This may not be possible with libraries that use properties files implicitly.

Edit: The methods described above have only been introduced in Java 1.6 - for older versions, you're out of luck, as dsadinoff wrote.

Michael Borgwardt
+2  A: 

Not unless you

  1. are running java 6 or later
  2. control the code loading the properties file, and can use a Reader. See the javadoc.

This is a pretty annoying flaw in the spec. There are several workarounds, probably the simplest being to auto-generate a unicode-escaped compliant .properties file from an encoding-appropriate (cp1250, utf-8, whatever) source.

Java ships with a transcoder called native2ascii to do this for you:

There are some aged RFEs on this subject:

djsadinoff
While it might be seen as a flaw in the spec, I think it's a good thing that the encoding of a .properties file is well-known and specified in the spec as opposed to being variable and non-defined.
Joachim Sauer
We certainly agree that it's good that the spec defines an encoding. It's bad that the spec neither defined a wide-gamut encoding like utf-8 nor a method of dynamically switching encoding early in the file, e.g. XML
djsadinoff
+1 for a useful answer
KLE
+1  A: 

If your properties file is available at build time, you can also convert it in your ant script using the native2ascii task:

<property name="javac.source.encoding" value="Cp1250"/>

<native2ascii src="${src.dir}" dest="${classes.dir}"
   encoding="${javac.source.encoding}"
   includes="**/*.properties"/>
Jörn Horstmann