代码如下:
import java.io.ByteArrayInputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import org.apache.commons.io.output.ByteArrayOutputStream;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.Writable;
import org.apache.hadoop.util.StringUtils;
public class WriatableTest {
//将IntWritable对象序列化和反序列化
public static byte[] serialize(Writable writable) throws IOException{
ByteArrayOutputStream out = new ByteArrayOutputStream();
DataOutputStream dataout = new DataOutputStream(out);
writable.write(dataout);
dataout.close();
return out.toByteArray();
}
public static byte[] deserialize(Writable writable, byte[] bytes) throws IOException{
ByteArrayInputStream in = new ByteArrayInputStream(bytes);
DataInputStream datain = new DataInputStream(in);
writable.readFields(datain);
datain.close();
return bytes;
}
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
IntWritable intwritable = new IntWritable(163);
byte[] bytes = serialize(intwritable);
System.out.println(bytes);
System.out.println(StringUtils.byteToHexString(bytes));
//assertThat(bytes.length, is(4));
//asserThat(StringUtils.byteToHexString(bytes), is("000000a3"));
IntWritable writable = new IntWritable();
byte[] bytest = deserialize(writable,bytes);
System.out.println(bytest);
System.out.println(writable.get());
}
}
输出:
[B@279f2327
000000a3
[B@279f2327
163