String的getBytes()方法是得到一個字串的字節數組,這是眾所周知的。但特別要注意的是,本方法將返回該操作系統默認的編碼格式的字節數組。如果你在使用這個方法時不考慮到這一點,你會發現在一個平台上運行良好的系統,放到另外一台機器后會產生意想不到的問題。比如下面的程序:
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); } } |
在一個中文WindowsXP系統下,運行時,結果為:
bytes lenght is:12 |
但是如果放到了一個英文的UNIX環境下運行:
$ java TestCharset bytes lenght is:9 |
如果你的程序依賴於該結果,將在后續操作中引起問題。為什么在一個系統中結果為12,而在另外一個卻變成了9了呢?上面已經提到了,該方法是和平台(編碼)相關的。
在中文操作系統中,getBytes方法返回的是一個GBK或者GB2312的中文編碼的字節數組,其中中文字符,各占兩個字節。而在英文平台中,一般的默認編碼是“ISO-8859-1”,每個字符都只取一個字節(而不管是否非拉丁字符)。
Java中的編碼支持
Java是支持多國編碼的,在Java中,字符都是以Unicode進行存儲的,比如,“你”字的Unicode編碼是“4f60”,我們可以通過下面的實驗代碼來驗證:
class TestCharset { public static void main(String[] args) { char c = '你'; int i = c; System.out.println(c); System.out.println(i); } } |
不管你在任何平台上執行,都會有相同的輸出:
20320 |
20320就是Unicode “4f60”的整數值。其實,你可以反編譯上面的類,可以發現在生成的.class文件中字符“你”(或者其它任何中文字串)本身就是以Unicode編碼進行存儲的:
char c = '/u4F60'; ... ... |
即使你知道了編碼的編碼格式,比如:
javac -encoding GBK TestCharset.java |
編譯后生成的.class文件中仍然是以Unicode格式存儲中文字符或字符串的。使用String.getBytes(String charset)方法
所以,為了避免這種問題,我建議大家都在編碼中使用String.getBytes(String charset)方法。下面我們將從字串分別提取ISO-8859-1和GBK兩種編碼格式的字節數組,看看會有什么結果:
package org.bruce.file.handle.experiment; class TestCharset3 { public static void main(String[] args) { new TestCharset3().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是兩個字節的, 而上面的Integer.toHexString會把字節擴展為4個字節 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(); } }
執行上面程序將打印出:
可見,在s中提取的8859-1格式的字節數組長度為9,中文字符都變成了“63”,ASCII碼為63的是“?”,一些國外的程序在國內中文環境下運行時,經常出現亂碼,上面布滿了“?”,就是因為編碼沒有進行正確處理的結果。 而提取的GBK編碼的字節數組中正確得到了中文字符的GBK編碼。字符“你”“好”“!”的GBK編碼分別是:“c4e3”“bac3”“a3a1”。得到了正確的以GBK編碼的字節數組,以后需要還原為中文字串時,可以使用下面方法:
mysql 不支持 unicode,所以比較麻煩。
將 connectionString 設置成 encoding 為 gb2312 String connectionString = "jdbc:mysql://localhost/test?useUnicode=true&characterEncoding=gb2312"; 測試代碼: String str = "漢字"; PreparedStatement pStmt = conn.prepareStatement("INSERT INTO test VALUES (?)"); pStmt.setString(1,str); pStmt.executeUpdate(); 數據庫表格: create table test ( name char(10) ) 連接 Oracle Database Server ------------------------------------------------------------------------------- 在把漢字字符串插入數據庫前做如下轉換操作: String(str.getBytes("ISO8859_1"),"gb2312") 測試代碼: String str = "漢字"; PreparedStatement pStmt = conn.prepareStatement("INSERT INTO test VALUES (?)"); pStmt.setString(1,new String(str.getBytes("ISO8859_1"),"gb2312"); pStmt.executeUpdate(); Servlet ------------------------------------------------------------------------------- 在 Servlet 開頭加上兩句話: response.setContentType("text/html;charset=UTF-8"); request.setCharacterEncoding("UTF-8"); JSP -------------------------------------------------------------------------------
|
1 @Test 2 public void testBytes(){ 3 //字節數 4 //中文:ISO:1 GBK:2 UTF-8:3 5 //數字或字母: ISO:1 GBK:1 UTF-8:1 6 String username = "中"; 7 try { 8 //得到指定編碼的字節數組 字符串--->字節數組 9 byte[] u_iso=username.getBytes("ISO8859-1"); 10 byte[] u_gbk=username.getBytes("GBK"); 11 byte[] u_utf8=username.getBytes("utf-8"); 12 System.out.println(u_iso.length); 13 System.out.println(u_gbk.length); 14 System.out.println(u_utf8.length); 15 //跟上面剛好是逆向的,字節數組---->字符串 16 String un_iso=new String(u_iso, "ISO8859-1"); 17 String un_gbk=new String(u_gbk, "GBK"); 18 String un_utf8=new String(u_utf8, "utf-8"); 19 System.out.println(un_iso); 20 System.out.println(un_gbk); 21 System.out.println(un_utf8); 22 //有時候必須是iso字符編碼類型,那處理方式如下 23 String un_utf8_iso=new String(u_utf8, "ISO8859-1"); 24 //將iso編碼的字符串進行還原 25 String un_iso_utf8=new String(un_utf8_iso.getBytes("ISO8859-1"),"UTF-8"); 26 System.out.println(un_iso_utf8); 27 28 } catch (UnsupportedEncodingException e) { 29 // TODO Auto-generated catch block 30 e.printStackTrace(); 31 } 32 }
測試結果:
1
2
3
?
中
中
ä¸
中
從轉載的文章摘:
亂碼原因:為什么使用ISO8859-1編碼再組合之后,無法還原"中"字呢,其實原因很簡單,因為ISO8859-1編碼的編碼表中,根本就沒有包含漢字字符,當然也就無法通過"中".getBytes("ISO8859-1");來得到正確的"中"字在ISO8859-1中的編碼值了,所以再通過new String()來還原就無從談起了.
有時候,為了讓中文字符適應某些特殊要求(如http header頭要求其內容必須為iso8859-1編碼),可能會通過將中文字符按照字節方式來編碼的情況,如:
String s_iso88591 = new String("中".getBytes("UTF-8"),"ISO8859-1"),這樣得到的s_iso8859-1字符串實際是三個在ISO8859-1中的字符,在將這些字符傳遞到目的地后,目的地程序再通過相反的方式String s_utf8 = new String(s_iso88591.getBytes("ISO8859-1"),"UTF-8")來得到正確的中文漢字"中".這樣就既保證了遵守協議規定、也支持中文.
轉自:http://blog.csdn.net/yang3wei/article/details/7381578 http://blog.csdn.net/techbirds_bao/article/details/8555449