String的getBytes()方法是得到一個(gè)字串的字節(jié)數(shù)組,這是眾所周知的。但特別要注意的是,本方法將返回該操作系統(tǒng)默認(rèn)的編碼格式的字節(jié)數(shù)組。如果你在使用這個(gè)方法時(shí)不考慮到這一點(diǎn),你會(huì)發(fā)現(xiàn)在一個(gè)平臺(tái)上運(yùn)行.
良好的系統(tǒng),放到另外一臺(tái)機(jī)器后會(huì)產(chǎn)生意想不到的問題。比如下面的程序,class TestCharset { public static void main(String[] args) { new TestCharset().execute(); } private void execute() { String s = "Hello!你好!"; byte[] bytes = s.getBytes(); System.out.println("bytes lenght is:" + bytes.length); }} Java中的編碼支持 Java是支持多國(guó)編碼的,在Java中,字符都是以Unicode進(jìn)行存儲(chǔ)的,比如,“你”字的Unicode編碼是“4f60”,我們可以通過下面的實(shí)驗(yàn)代碼來驗(yàn)證: class TestCharset { public static void main(String[] args) { char c = '你'; int i = c; System.out.println(c); System.out.println(i); }} 20320就是Unicode “4f60”的整數(shù)值。其實(shí),你可以反編譯上面的類,可以發(fā)現(xiàn)在生成的.class文件中字符“你”(或者其它任何中文字串)本身就是以Unicode編碼進(jìn)行存儲(chǔ)的: char c = '\u4F60'; ... ... 即使你知道了編碼的編碼格式,比如:
javac -encoding GBK TestCharset.java 編譯后生成的.class文件中仍然是以Unicode格式存儲(chǔ)中文字符或字符串的。 使用String.getBytes(String charset)方法 所以,為了避免這種問題,我建議大家都在編碼中使用String.getBytes(String charset)方法。下面我們將從字串分別提取ISO-8859-1和GBK兩種編碼格式的字節(jié)數(shù)組,看看會(huì)有什么結(jié)果: class TestCharset { public static void main(String[] args) { new TestCharset().execute(); } private void execute() { String s = "Hello!你好!"; byte[] bytesISO8859 =null; byte[] bytesGBK = null; try { bytesISO8859 = s.getBytes("iso-8859-1"); bytesGBK = s.getBytes("GBK"); } catch (java.io.UnsupportedEncodingException e) { e.printStackTrace(); } System.out.println("-------------- \n 8859 bytes:"); System.out.println("bytes is: " + arrayToString(bytesISO8859)); System.out.println("hex format is:" + encodeHex(bytesISO8859)); System.out.println(); System.out.println("-------------- \n GBK bytes:"); System.out.println("bytes is: " + arrayToString(bytesGBK)); System.out.println("hex format is:" + encodeHex(bytesGBK)); } public static final String encodeHex (byte[] bytes) { StringBuffer buff = new StringBuffer(bytes.length * 2); String b; for (int i=0; i<bytes.length ; i++) { b = Integer.toHexString(bytes[i]); // byte是兩個(gè)字節(jié)的,而上面的Integer.toHexString會(huì)把字節(jié)擴(kuò)展為4個(gè)字節(jié) buff.append(b.length() > 2 ? b.substring(6,8) : b); buff.append(" "); } return buff.toString(); } public static final String arrayToString (byte[] bytes) { StringBuffer buff = new StringBuffer(); for (int i=0; i<bytes.length ; i++) { buff.append(bytes[i] + " "); } return buff.toString(); }} -------------- 8859 bytes:bytes is: 72 101 108 108 111 33 63 63 63hex format is:48 65 6c 6c 6f 21 3f 3f 3f-------------- GBK bytes:bytes is: 72 101 108 108 111 33 -60 -29 -70 -61 -93 -95hex format is:48 65 6c 6c 6f 21 c4 e3 ba c3 a3 a1 可見,在s中提取的8859-1格式的字節(jié)數(shù)組長(zhǎng)度為9,中文字符都變成了“63”,ASCII碼為63的是“?”,一些國(guó)外的程序在國(guó)內(nèi)中文環(huán)境下運(yùn)行時(shí), 經(jīng)常出現(xiàn)亂碼,上面布滿了“?”,就是因?yàn)榫幋a沒有進(jìn)行正確處理的結(jié)果。而提取的GBK編碼的字節(jié)數(shù)組中正確得到了中文字符的GBK編碼。字符“你”“好”“!”的GBK編碼分別是:“c4e3”“bac3”“a3a1”。得到了正確的以GBK編碼的字節(jié)數(shù)組,以后需要還原為中文字串時(shí),可以使用下面方法: |
|