近日由于公司的一台oracle数据库的编码问题,造成取出来的数据都是乱码。
原来数据库存进去时是utf-8编码的,现在数据库的字符集变成了gbk编码,所以只能在程序里转换下:
new String(str.getBytes("GBK"), "UTF-8");
下面这个是在网上说的一个比较好的方面,不过,没去试
我们都知道,在 JVM 内部,所有的字符串都是转换成为 Unicode 编码来处理的。我们从一个 GBK 编码的文本中读取的内容,写到另外一个 UTF-8 编码的文本文件中去,并不会出现乱码的问题。似乎可以猜测到,我们可以利用 Java IO 中的 Stream 来良好的处理内码转换的问题。为了方便起见,可以借助 Apache Commons-IO 项目中提供的实用工具来编写代码。
/* gbkString 为一 GBK 编码的字符串 */
String utf8String = IOUtils.toString(IOUtils.toInputStream(gbkString, "UTF-8"));
utf8String中字符,皆变为 UTF-8 编码。
附,com.apache.commons.io.IOUtils 中相关代码如下:
/**
* Convert the specified string to an input stream, encoded as bytes
* using the specified character encoding.
*
* Character encoding names can be found at
* IANA.
*
* @param input the string to convert
* @param encoding the encoding to use, null means platform default
* @throws IOException if the encoding is invalid
* @return an input stream
* @since Commons IO 1.1
*/
public static InputStream toInputStream(String input, String encoding) throws IOException {
byte[] bytes = encoding != null ? input.getBytes(encoding) : input.getBytes();