`

Hbase中文字符与byte[]的转换

阅读更多
Hbase客户端信息采用byte[]与服务器进行通信,中文字符与byte[]的转换的转换有两种方式:

1.采用String类自带的函数
String s  = "你好中国";
byte [] b = s.getBytes();
对应的byte[]转换为String为:
s = new String(s.getBytes());

2.采用org.apache.hadoop.hbase.util.Bytes类的函数
String s  = "你好中国";
byte [] b = Bytes.toBytes(s);
对应的byte[]转换为String为:
s = Bytes.toString(Bytes.toBytes(s));

方法1 与方法2 都能完成自己的转换,输出也正常。
但是两种方法不能混合使用,因为两种方法中b值却一样,
方法1:b = [-60, -29, -70, -61, -42, -48, -71, -6]
方法2:b = [-28, -67, -96, -27, -91, -67, -28, -72, -83, -27, -101, -67]
原因在于换行的时候采用的Charset不一致
在方法2中 Bytes.toBytes(s); 最后调用的是String类中的s.getBytes("UTF-8");而不是s.getBytes()。
s.getBytes("UTF-8")与s.getBytes()最后都调用了的
static byte[] encode(String charsetName, char[] ca, int off, int len)
关键在于charsetName不同。
在看s.getBytes()最后的charsetName,
产生的函数为:
    public static Charset defaultCharset() {
        if (defaultCharset == null) {
    synchronized (Charset.class) {
java.security.PrivilegedAction pa =
    new GetPropertyAction("file.encoding");
String csn = (String)AccessController.doPrivileged(pa);
Charset cs = lookup(csn);
if (cs != null)
    defaultCharset = cs;
                else
    defaultCharset = forName("UTF-8");
            }
}
return defaultCharset;
    }
跟系统参数file.encoding的值有关,查看下本机的file.encoding
System.out.println(System.getProperty("file.encoding"));
值为GB18030,因此以上两种方式产生的byte[]自然不同,
因此Hbase中文字符与byte[]的转换要统一编码格式,全部采用方法2最好,如果要使用String类的方法
使用方法如下:
String s  = "你好中国";
byte [] b = s.getBytes("UTF-8");
对应的byte[]转换为String为:
s = new String(Bytes.toBytes(s),"UTF-8");

以上区别只针对与中文的转换,数字与英文以及"`~!@#$%^&*()_+=-|[]{}\\/.,<>?"没有区别!!
2
2
分享到:
评论
1 楼 Mybeautiful 2011-11-23  
写的很好..

相关推荐

Global site tag (gtag.js) - Google Analytics