hadoop之Writable序列化

来源:互联网 发布:千里眼淘宝插件 编辑:程序博客网 时间:2024/05/18 00:54

代码如下:

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 stubIntWritable 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@279f2327000000a3[B@279f2327163



0 0