Java problems with UTF-8 in different OS

2019-05-30 15:49发布

问题:

I'm programing with other people an application to college homework, and sometime we use non-english characters in comments or in Strings displayed in the views. The problem is that everyone of use is using a different OS and sometimes different IDE's to program.

Concretely, one is using MacOS, another Windows7, and another and me Ubuntu Linux. Furthermore, all of them use Eclipse and I use gedit. We have no idea if Eclipse or gedit are configurable to work propertly with UTF8 bussiness, at least I don't found nothing for mine.

The fact is that what I write with non-english characters appears in Windows & MacOS virtual machines with strange symbols and vice-versa , and sometimes, what my non-linux friends write provokes compilation warnings like this: warning: unmappable character for encoding UTF8.

Do you have any Idea to solve this? It is not really urgent but it will be a help.

Thank you.

回答1:

Not sure about gedit, but you can certainly configure eclipse to use whatever encoding you like for source code. It's part of the project properties (and saved in the .settings directory within the project).



回答2:

Eclipse works fine with UTF-8. See Michael's answer about configuring it. Maybe for Windows and/or MacOS it is really necessary. Ubuntu uses UTF-8 as the default encoding so I don't think it's necessary to configure Eclipse there.

As for Gedit, this picture shows that it is possible to change the encoding when saving a file in Gedit.

Anyway, you need to make sure that all of you use UTF-8 for your sources. This is the only reasonable way to achieve cross-platform portability of your sources.



回答3:

You could avoid the issue in Strings by using character escape sequences, and using only ASCII encoding for the files.

For example, an en dash can be expressed as "\u2013".

You can quickly search for the Java code for individual characters here.

As Sergey notes below, this works best for small numbers of non-ASCII characters. An alternative is to put all the UTF-8 strings in resource files. Eclipse provides a handy wizard for this.



回答4:

If your UTF8 file contains a BOM (byte order mark) then you will have a problem. It is a known bug , see here and here.

The BOM is optional with UTF8 and most of the time it is not there because it breaks many tools (like Javadoc, XML parser,...).

More info here.