Java 读取 MySQL 中文 乱码
场景:Java,eclipse,读取MySQL数据库,MySQL编码为utf-8
问题:读出来的中文在eclipse的输出窗口中显示为乱码
错误的写法
1
System.out.print(new String( rs.getString("bib_author").getBytes("utf-8"),"GBK" ));
2
System.out.print( rs.getString("bib_author"));
Java中统一使用Unicode编码。
正确的写法:
System.out.print(new String (rs.getBytes("bib_author"),"utf-8") + " ");
如划线加粗部分所示,应该先用二进制方式读进来,然后再转化为utf-8方式,和数据库中的编码一致。
下面是之前碰到过的一个例子,从web服务器读取数据,并转化为utf-8。web服务器使用的是iso-8859-1编码。
同样也是先用getbytes方式先获取二进制流,然后转成utf-8。
-------------------------------------------------------------------------------------------
3个地方设置编码,解决乱码问题
public static String GetResponse(HttpMethodBase Method) throws IOException {
String charset= Method.getResponseCharSet();
System.out.println("返回的字符编码为:"+charset);
InputStream responseBody = Method.getResponseBodyAsStream();
// BufferedReader br = new BufferedReader(new InputStreamReader(responseBody));
BufferedReader br = new BufferedReader(new InputStreamReader(Method.getResponseBodyAsStream(), "ISO-8859-1"));//1
String tempbf;
StringBuffer htmlbf = new StringBuffer(100);
while ((tempbf = br.readLine()) != null) {
// htmlbf.append(tempbf);
htmlbf.append(new String(tempbf.getBytes("iso-8859-1"),"utf-8"));//2
htmlbf.append("/n");
}
return htmlbf.toString();
}//end GetResponse
然后在构建GetMethod或PostMethod时也指定编码
Method.addRequestHeader("Content-Type","application/x-www-form-urlencoded;charset=utf-8");//3
或者 NameValuePair p2 = new NameValuePair( "Content-Type","text/html; charset=utf-8");
post.setRequestBody( new NameValuePair[]{p2})//3