Android - 适用于所有语言的字符串编码

时间:2013-12-30 08:00:44

标签: java android encoding character-encoding

我正在开发Android应用程序,涉及显示多种语言的字符串。例如,中文可能需要UTF-8编码,而日语可能需要ShiftJS。我想知道是否有针对这种情况的通用解决方案来正确显示所有(或大多数)语言字符串?

谢谢!

1 个答案:

答案 0 :(得分:2)

只有在从外部源(例如文件)构造String对象时以及将String对象转换为外部表单(例如文件)时,才需要担心UTF-8或Shift_JIS。相反,如果您已经有一个String对象,则不必担心UTF-8或Shift_JIS。

构造String对象时:

// HIRAGANA LETTER A (U+3042), encoded in UTF-8.
byte[] rawDataEncodedInUTF8 = { (byte)0xE3, (byte)0x81, (byte)0x82 };
// Convert to a String object from the bytes.
String a1 = new String(rawDataEncodedInUTF8, "UTF-8");

// HIRAGANA LETTER A (U+3042), encoded in Shift_JIS.
byte[] rawDataEncodedInShiftJIS = { (byte)0x82, (byte)0xA0 };
// Convert to a String object from the bytes.
String a2 = new String(rawDataEncodedInShiftJIS, "Shift_JIS");

// Both a1 and a2 represent HIRAGANA LETTER A (U+3042).
// So, a1.equals(a2) is true.

// String.charAt(int) returns a character at the index in
// UTF-16BE, so c here is 0x3042. Note that the meaning of
// 'U+3042' and that of '0x3042 in UTF-16BE' are different.
char c = a1.charAt(0);

构建外部表单时:

String text = ...;

byte[] rawDataEncodedInUTF8     = text.getBytes("UTF-8");
byte[] rawDataEncodedInShiftJIS = text.getBytes("Shift_JIS");

首先,您需要了解(1)Unicode及其编码(UTF-8 / UTF-16BE / UTF-16LE / ...)和(2)Java使用Unicode之间的区别。然后,我建议您在将数据保存到文件,数据库和任何其他外部位置时使用UTF-8。

相关问题