我写的代码:
/**
* 用getBytes(encoding):返回字符串的一个byte数组
* 当b[0]为 63时,应该是转码错误
* A、不乱码的汉字字符串:
* 1、encoding用GB2312时,每byte是负数;
* 2、encoding用ISO8859_1时,b[i]全是63。
* B、乱码的汉字字符串:
* 1、encoding用ISO8859_1时,每byte也是负数;
* 2、encoding用GB2312时,b[i]大部分是63。
* C、英文字符串
* 1、encoding用ISO8859_1和GB2312时,每byte都大于0;
* <p/>
* 总结:给定一个字符串,用getBytes("iso8859_1")
* 1、如果b[i]有63,不用转码; A-2
* 2、如果b[i]全大于0,那么为英文字符串,不用转码; B-1
* 3、如果b[i]有小于0的,那么已经乱码,要转码。 C-1
*/
private static String toGb2312(String str) {
if (str == null) return null;
String retStr = str;
byte b[];
try {
b = str.getBytes("ISO8859_1"); for (int i = 0; i < b.length; i++) {
byte b1 = b[i];
if (b1 == 63)
break; //1
else if (b1 > 0)
continue;//2
else if (b1 < 0) { //不可能为0,0为字符串结束符
retStr = new String(b, "GB2312");
break;
}
}
} catch (UnsupportedEncodingException e) {
// e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
return retStr;
}
/**
* 用getBytes(encoding):返回字符串的一个byte数组
* 当b[0]为 63时,应该是转码错误
* A、不乱码的汉字字符串:
* 1、encoding用GB2312时,每byte是负数;
* 2、encoding用ISO8859_1时,b[i]全是63。
* B、乱码的汉字字符串:
* 1、encoding用ISO8859_1时,每byte也是负数;
* 2、encoding用GB2312时,b[i]大部分是63。
* C、英文字符串
* 1、encoding用ISO8859_1和GB2312时,每byte都大于0;
* <p/>
* 总结:给定一个字符串,用getBytes("iso8859_1")
* 1、如果b[i]有63,不用转码; A-2
* 2、如果b[i]全大于0,那么为英文字符串,不用转码; B-1
* 3、如果b[i]有小于0的,那么已经乱码,要转码。 C-1
*/
private static String toGb2312(String str) {
if (str == null) return null;
String retStr = str;
byte b[];
try {
b = str.getBytes("ISO8859_1"); for (int i = 0; i < b.length; i++) {
byte b1 = b[i];
if (b1 == 63)
break; //1
else if (b1 > 0)
continue;//2
else if (b1 < 0) { //不可能为0,0为字符串结束符
retStr = new String(b, "GB2312");
break;
}
}
} catch (UnsupportedEncodingException e) {
// e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
return retStr;
}
解决方案 »
- 自定义异常用得多吗
- 关于JScrollPane滚动条置顶的小问题
- 精通Swing的来指教下
- java线程互斥问题
- 设计模式之问,请帮忙
- 关于文件缓冲(新手问题)
- 请问下面addPlant_sum方法中的revWeek是如何获得的
- 在Java中如何屏蔽系统热键
- 请教一个“Java代码的运行时错误原因”与修改办法...
- [遇到这个问题的人多吗?]Connection reset by peer: JVM_recv in socket input stream read
- 100分求一个算法,用java实现:根据输入小数点后的位数,来输出PI的值。解决立即给分,在线等!
- J2SDK的中文字体问题,请进来侃侃
String content = req.getParameter("studentCriticContent");
content = new String(content.getBytes("ISO8859_1"),"gb2312");