---
title: "Hadoop的Text类getBytes字节数据put到HBase后有多余字符串问题"
author: "BlackWing"
date: "2013-11-21T15:53:25Z"
tags: []
categories: ["开源软件"]
slug: "hadoop-text-getbytes-put-hbase"
draft: false
lastmod: "2013-11-21T15:54:59Z"
id: 1978501
url: "https://blackwing.iteye.com/blog/1978501"
---

转载请标明出处：http://blackwing.iteye.com/blog/1978501

org.apache.hadoop.io.Text里面的getBytes方法有个小坑。

先看现场：

```java

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得到的数据如下：

```java

91223224-20131120-96413376-150\x00\x00\x00
91223224-20131120-96413376-150

```


原因是getBytes获得的字节数组长度跟Text.getLength获得的长度不一致，不足的地方Text会自动补全。

```java

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()