(透彻)java String.getBytes()编码问题
2012-03-22 03:04
459 查看
转载自:
String.getBytes()的问题 String的getBytes()方法是得到一个字串的字节数组,这是众所周知的。但特别要注意的是,本方法将返回该操作系统默认的编码格式的字节数组。如果你在使用这个方法时不考虑到这一点,你会发现在一个平台上运行良好的系统,放到另外一台机器后会产生意想不到的问题。比如下面的程序:
在中文操作系统中,getBytes方法返回的是一个GBK或者GB2312的中文编码的字节数组,其中中文字符,各占两个字节。而在英文平台中,一般的默认编码是“ISO-8859-1”,每个字符都只取一个字节(而不管是否非拉丁字符)。 Java中的编码支持 Java是支持多国编码的,在Java中,字符都是以Unicode进行存储的,比如,“你”字的Unicode编码是“4f60”,我们可以通过下面的实验代码来验证:
所以,为了避免这种问题,我建议大家都在编码中使用String.getBytes(String charset)方法。下面我们将从字串分别提取ISO-8859-1和GBK两种编码格式的字节数组,看看会有什么结果: package org.bruce.file.handle.experiment; 执行上面程序将打印出:
而提取的GBK编码的字节数组中正确得到了中文字符的GBK编码。字符“你”“好”“!”的GBK编码分别是:“c4e3”“bac3”“a3a1”。得到了正确的以GBK编码的字节数组,以后需要还原为中文字串时,可以使用下面方法:
将 connectionString 设置成 encoding 为 gb2312 String connectionString = "jdbc:mysql://localhost/test?useUnicode=true&characterEncoding=gb2312"; 测试代码: String str = "汉字"; PreparedStatement pStmt = conn.prepareStatement("INSERT INTO test VALUES (?)"); pStmt.setString(1,str); pStmt.executeUpdate(); 数据库表格: create table test ( name char(10) ) 连接 Oracle Database Server ------------------------------------------------------------------------------- 在把汉字字符串插入数据库前做如下转换操作: String(str.getBytes("ISO8859_1"),"gb2312") 测试代码: String str = "汉字"; PreparedStatement pStmt = conn.prepareStatement("INSERT INTO test VALUES (?)"); pStmt.setString(1,new String(str.getBytes("ISO8859_1"),"gb2312"); pStmt.executeUpdate(); Servlet ------------------------------------------------------------------------------- 在 Servlet 开头加上两句话: response.setContentType("text/html;charset=UTF-8"); request.setCharacterEncoding("UTF-8"); JSP ------------------------------------------------------------------------------- |
相关文章推荐
- (透彻)java String.getBytes()编码问题
- (透彻)java String.getBytes()编码问题
- 深入解析java String中getBytes()的编码问题
- java String.getBytes()编码问题——String.getBytes(charset)
- java中String的getBytes编码问题
- Java里面String的编码问题
- String.getBytes()方法中的中文编码问题
- String.getBytes()编码问题
- String.getBytes()方法中的中文编码问题
- String.getBytes()方法中的中文编码问题
- 网站开发进阶(三十六)String.getBytes()方法中的中文编码问题
- 网站开发进阶(三十六)String.getBytes()方法中的中文编码问题
- String.getBytes()方法中的中文编码问题
- 用java String类的getBytes(String charsetName)和String(byte[] bytes, String charsetName)解决乱码问题
- String.getBytes()方法中的中文编码问题
- [Java]_[初级]_[utf8编码的byte[]数组转换为String时要注意的问题]
- Java之由String.getBytes()说编码
- String.getBytes()方法中的中文编码问题(转)
- mysql的utf8mb4编码以及java.sql.SQLException: Incorrect string value: '\xF0\x9F\x92\x94' 问题的处理
- [Java]_[初级]_[utf8编码的byte[]数组转换为String时要注意的问题]