即使你知道了编码的编码格式,比如: javac -encoding GBK TestCharset.java 编译后生成的.class文件中仍然是以Unicode格式存储中文字符或字符串的。 使用String.getBytes(String charset)方法 所以,为了避免这种问题,我建议大家都在编码中使用String.getBytes(String charset)方法。下面我们将从字串分别提取ISO-8859-1和GBK两种编码格式的字节数组,看看会有什么结果: 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是两个字节的,而上面的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(); }} -------------- 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格式的字节数组长度为9,中文字符都变成了“63”,ASCII码为63的是“?”,一些国外的程序在国内中文环境下运行时, 经常出现乱码,上面布满了“?”,就是因为编码没有进行正确处理的结果。而提取的GBK编码的字节数组中正确得到了中文字符的GBK编码。字符“你”“好”“!”的GBK编码分别是:“c4e3”“bac3”“a3a1”。得到了正确的以GBK编码的字节数组,以后需要还原为中文字串时,可以使用下面方法: |
闂傚倸鍊搁崐宄懊归崶顒€违闁逞屽墴閺屾稓鈧綆鍋呭畷宀勬煛瀹€鈧崰鏍€佸☉妯峰牚闁告劗鍋撳В澶嬩繆閻愵亜鈧垿宕曢弻銉ュ瀭闁秆勵殔閽冪喖鏌i弮鍥モ偓鈧柛瀣尭閳藉鈻嶉褌绨奸柟渚垮姂瀹曟儼顦柡鈧懞銉d簻闁哄洨鍋為ˉ鐐烘倵濮樼偓瀚�闂傚倸鍊搁崐椋庣矆娓氣偓楠炴牠顢曢妶鍡椾粡濡炪倖鍔х粻鎴犲閸ф鐓曢柟閭﹀灱閸ゅ鏌ら弶鎸庡仴闁哄本绋戦埥澶娾枎閹邦喚鈻忕紓鍌氬€风拋鏌ュ疾閻樿钃熼柣鏃傗拡閺佸秵绻濇繝鍌氭灓闁哄棭鍘奸—鍐Χ閸愩劌濮烽梺鐟板殩閹凤拷>>
正在阅读:String.getBytes()方法中的中文编码问题String.getBytes()方法中的中文编码问题
2004-04-08 14:38
出处:Javajia
责任编辑:sdq
键盘也能翻页,试试“← →”键