getByte详解---读取数据库读取技巧和应用实例

String newStr = new String(oldStr.getBytes(), "UTF-8");

java中的String类是按照unicode进行编码的, 即在java处理时为unicode方式。oldStr.getBytes( String encoding)则是将java内部存在的unicode编码的String处理为encoding指定格式的byte[]字节数组,默认为由jdk查询的操作系统默认编码方式!

当使用String(byte[] bytes, String encoding)构造字符串时,encoding所指的是bytes中的数据是按照那种方式编码的,而不是最后产生的String是什么编码方式,换句话说,是让系统把bytes中的数据由encoding指定的编码方式转换成unicode编码。如果不指明,bytes的编码方式将由jdk根据操作系统默认编码方式决定。

        当我们从文件中读数据时,最好使用InputStream方式,然后采用String(byte[] bytes, String encoding)指明文件的编码方式。不要使用Reader方式,因为Reader方式会自动根据jdk指明的编码方式把文件内容转换成unicode 编码。

        当我们从数据库中读文本数据时,采用ResultSet.getBytes()方法取得字节数组,同样采用带编码方式的字符串构造方法即可。

ResultSet rs;
bytep[] bytes = rs.getBytes();
String str = new String(bytes, "gb2312");

不要采取下面的步骤。

ResultSet rs;
String str = rs.getString();
str = new String(str.getBytes("iso8859-1"), "gb2312");

        这种编码转换方式效率底。之所以这么做的原因是,ResultSet在getString()方法执行时,默认数据库里的数据编码方式为 iso8859-1。系统会把数据依照iso8859-1的编码方式转换成unicode。使用str.getBytes("iso8859-1")把数据还原,然后利用new String(bytes, "gb2312")把数据从gb2312转换成unicode,中间多了好多步骤。 
class testCharset { public static void main(String[] args) { new testCharset().execute(); } private void execute() { String s = "Hello!你好!"; byte[] bytesISO8859 =null; byte[] bytesGBK = null; try { bytesISO8859 = s.getBytes("iso-8859-1"); bytesGBK = s.getBytes("GBK"); } catch(java.io.UnsupportedEncodingException e) { e.printStackTrace(); } System.out.println("-------------- 8859 bytes:"); System.out.println("bytes is: " + arrayToString(bytesISO8859)); System.out.println("hex format is:"+ encodeHex(bytesISO8859)); System.out.println();//在s中提取的8859-1格式的字节数组长度为9,中文字符都变成了“63”,ASCII码为63的是“?”, System.out.println ("-------------- GBK bytes:"); System.out.println("bytes is:" + arrayToString(bytesGBK)); System.out.println("hex formatis:" + encodeHex(bytesGBK)); } public static final String encodeHex (byte[] bytes) { StringBuffer buff = new StringBuffer(bytes.length * 2); String b; for (int i=0; i 2 ? b.substring(6,8) : b); //buff.append(b); buff.append(" "); } return buff.toString(); } public static final String arrayToString (byte[] bytes) {//字节数组保存自己的字节以十进制整数保存的................ StringBuffer buff = new StringBuffer(); for (int i=0; i       

你可能感兴趣的:(getByte详解---读取数据库读取技巧和应用实例)