Last active
October 12, 2017 06:51
-
-
Save nobodxbodon/04c1331022eabda0b4ae883af0329293 to your computer and use it in GitHub Desktop.
win1252(cp1252), iso8859, utf8转换乱码问题 http://bbs.csdn.net/topics/390010852
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.io.UnsupportedEncodingException; | |
import java.nio.charset.Charset; | |
/** | |
* 原问题在 http://bbs.csdn.net/topics/390010852: | |
* 代码如下: | |
try | |
{ | |
PreparedStatement preStmt = con.prepareStatement("insert into t_bb(f_no,f_name) values(?,?)"); | |
preStmt.setString(1,"ABCDEFG"); | |
preStmt.setString(2,"中国从前有个传说"); | |
preStmt.executeUpdate(); | |
} | |
catch(SQLException e) | |
{ | |
System.out.println(new String(e.toString().getBytes("iso-8859-1"),"utf-8")); | |
} | |
<p>执行插入数据失败后,提示如下: | |
Duplicate entry 'ABCDEFG-中�?��?�??�??个传说' for key 'PRIMARY' | |
部分中文能正常显示,而部分为乱码,这是怎么回事? | |
* | |
*/ | |
public class 乱码溯因 { | |
public static void main(String[] 参数) throws UnsupportedEncodingException { | |
String 初始字符串 = "中国从前有个传说"; | |
// 受 http://blog.csdn.net/zyf814/article/details/17021949 启发 | |
String 编码1 = "utf-8"; | |
String 编码2 = "windows-1252"; | |
String 编码3 = "iso-8859-1"; | |
String 编码4 = "utf-8"; | |
byte[] 字节 = 初始字符串.getBytes(编码1); | |
System.out.println("UTF8表示:\n" + encodeHex(字节)); | |
String 转编码后 = new String(字节, 编码2); | |
System.out.println(编码2 + "表示:\n" + encodeHex(转编码后.getBytes(编码2))); | |
byte[] 转码字节 = 转编码后.getBytes(编码3); | |
System.out.println(编码3 + "表示:\n" + encodeHex(转码字节)); | |
String 二转编码后 = new String(转码字节, 编码4); | |
System.out.println(编码4 + "表示:\n" + encodeHex(二转编码后.getBytes(编码4))); | |
System.out.println(二转编码后); | |
} | |
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(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment