java.io.FileWriter class doesn’t use UTF-8 by default

来源:互联网 发布:考勤软件 编辑:程序博客网 时间:2024/06/06 05:32

Oddly enough the java.io.FileWriter class doesn’t use UTF-8 by default. I’m not exactly sure what the default encoding is (possibly ISO-8859-1 or US-ASCII?) but it doesn’t seem to be UTF-8, which is odd given that java strings are supposed to be unicode. This causes a problem if you want to have non-ascii characters and you don’t realise what’s happening. This was a bug in SQLEditor and somebody accidentally typed an umlaut into one of the fields and the file wouldn’t reload. (Which was annoying).

The correct thing to do seems to be to use the following:

OutputStreamWriter out = new OutputStreamWriter(new FileOutputStream(path),"UTF-8");

Which ensures that you are using UTF-8.

I suppose that the motivation for this is that it means that simple use of FileWriter is compatible with applications that are not unicode aware and don’t support UTF-8. It probably makes sense at some level, but it just goes to show that you can’t assume anything. :-)

0 0