浅谈java乱码问题
最近做通信部分,在发送中文的时候遇到了乱码问题。纠结了很久终于找到了答案解决的问题。
乱码往往是字符集不统一造成的,而笔者的程序中却是另一种情况引起的。message += (char)ins.read();
就是因为这句代码。。。
原因是这样的:用char强制转型时,只能转换0—127之间的ASCII码,而我们的中文(在GBK/GB2312字符集中中文由两个字节表示,而这连个字节不再0-127范围之内)的字节经char强制转型出来的就是“?”了。
对此我的解决方案是把每个对到的字节都放入字节队列中,在转成数组,最后用String(bytes[])转成字符串。代码如下
read = bufferedInputStream.read(); byte byte1 = (byte)read;bytes.add(byte1);messageRead = new String(listToBytes(bytes));
public static void compareCharset() {byte[] bytes1, bytes2, bytes3, bytes4, bytes5, bytes6, bytes7;String string = "a马";try {bytes1 = string.getBytes("GBK");System.out.println("以GBK编码程字节长度为" + bytes1.length);for (int i = 0; i < bytes1.length; i++) {System.out.println("以GBK编码每个字节是" + bytes1[i]);}bytes2 = string.getBytes("GB2312");System.out.println("以GB2312编码程字节长度为" + bytes2.length);for (int i = 0; i < bytes2.length; i++) {System.out.println("以GB2312编码每个字节是" + bytes2[i]);}bytes3 = string.getBytes("ISO-8859-1");System.out.println("以ISO-8859-1编码程字节长度为" + bytes3.length);for (int i = 0; i < bytes3.length; i++) {System.out.println("以ISO-8859-1编码每个字节是" + bytes3[i]);}bytes4 = string.getBytes("ASCII");System.out.println("以ASCII编码程字节长度为" + bytes4.length);for (int i = 0; i < bytes4.length; i++) {System.out.println("以ASCII编码每个字节是" + bytes4[i]);}bytes5 = string.getBytes("UTF-8");System.out.println("以UTF-8编码程字节长度为" + bytes5.length);for (int i = 0; i < bytes5.length; i++) {System.out.println("以UTF-8编码每个字节是" + bytes5[i]);}bytes7 = string.getBytes("UNICODE");System.out.println("以UNICODE编码程字节长度为" + bytes7.length);for (int i = 0; i < bytes7.length; i++) {System.out.println("以UNICODE编码每个字节是" + bytes7[i]);}} catch (Exception e) {e.printStackTrace();System.out.println("有不支持的字符集存在");}}