Hadoop的Text類getBytes字節數據put到HBase後有多餘字符串問題

轉載請標明出處:http://blackwing.iteye.com/blog/1978501

org.apache.hadoop.io.Text裏面的getBytes方法有個小坑。

先看現場:

String s = "91223224-20131120-96413376-150";
Text t = new Text();
t.set(s);
Put put = new Put(t.getBytes());//*1
put.add("kq".getBytes(), "0".getBytes(),"1".getBytes());
List<Put> puts = new ArrayList<Put>();
puts.add(put);
Put put2 = new Put(t.toString().getBytes());//*2
put2.add("kq".getBytes(), "1".getBytes(),"2".getBytes());
puts.add(put2);
try {
table.batch(puts);
table.flushCommits();
table.close();
} catch (Exception e) {
e.printStackTrace();
}

其中標註的地方就是差別所在。如果按照*1方式put到hbase,跟按照*2方式put到hbase得到的數據如下:

91223224-20131120-96413376-150\x00\x00\x00
91223224-20131120-96413376-150


原因是getBytes獲得的字節數組長度跟Text.getLength獲得的長度不一致,不足的地方Text會自動補全。

String s = "91223224-20131120-96413376-150";
Text t = new Text();
t.set(s);
System.out.println(t.getLength()+" | "+t.getBytes().length);

輸出結果是:30 | 33

所以如果要把Text的內容put到hbase,最保險的方式是先轉換爲String在獲得字節數組Text.toString().getBytes()
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章