Producing valid XML with Java and UTF-8 encoding

Use a FileOutputStream rather than a FileWriter.

The latter applies its own encoding, which is almost certainly not UTF-8 (depending on your platform, it’s probably Windows-1252 or IS-8859-1).

Edit (now that I have some time):

An XML document without a prologue is permitted to be encoded as UTF-8 or UTF-16. With a prologue, it iss allowed to specify its encoding (the prologue can contain only US-ASCII characters, so prologue is always readable).

A Reader deals with characters; it will decode the byte stream of the underlying InputStream. As a result, when you pass a Reader to the parser, you are telling it that you’ve already handled the encoding, so the parser will ignore the prologue. When you pass an InputStream (which reads bytes), it does not make this assumption, and will look to the prologue to define the encoding — or default to UTF-8/UTF-16 if it’s not there.

I’ve never tried reading a file that is encoded in UTF-16. I suspect that the parser will look for a Byte Order Mark (BOM) as the first 2 bytes of the file.

Leave a Comment