Can I use java.util.Properties with encoding different then default?
-
1Out of curiosity: Why would you need that? You'd break the assumptions of all the halfway-reasonable tools that handle .properties files. – Joachim Sauer Sep 01 '09 at 10:40
-
I use properties file as map written to disk. – IAdapter Sep 01 '09 at 12:03
3 Answers
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.

- 342,105
- 78
- 482
- 720
Not unless you
- are running java 6 or later
- 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:

- 5,519
- 6
- 33
- 40
-
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 Sep 01 '09 at 10:54
-
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 Sep 01 '09 at 11:01
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"/>

- 33,639
- 11
- 75
- 118