测试序列化后的长度
提示:需要用到的类,以及继承关系如下:
1.java.lang.Object |__ java.io.OutputStream |__ java.io.ByteArrayOutputStream //description public class ByteArrayOutputStream extends OutputStream //method byte[] toByteArray() //Creates a newly allocated byte array. 2.java.lang.Object |__ java.io.OutputStream |__ java.io.FilterOutputStream |__ java.io.DataOutputStream //description public class DataOutputStream extends FilterOutputStream implements DataOutput 3. java.lang.Object |__ java.io.OutputStream // description public abstract class OutputStream extends Object implements Closeable, Flushable //mdthods void close() void flush() void write(byte[] b) void write(byte[] b, int off, int len) abstract void write(int b) 4.org.apache.hadoop.io Interface Writable //description public interface Writable //methods void readFields(DataInput in) void write(DataOutput out) 5. java.lang.Object |__ org.apache.hadoop.io.IntWritable //description public class IntWritableextends Object implements WritableComparable // methods int get() void readFields(DataInput in) void set(int value) void write(DataOutput out) 6. java.lang.Object |__ org.apache.hadoop.util.StringUtils //description public class StringUtils extends Object //method static String byteToHexString(byte[] bytes) static String capitalize(String s) static String[] split(String str) static Path[] stringToPath(String[] str) static URI[] stringToURI(String[] str) static String uriToString(URI[] uris)
代码:
import java.io.DataOutputStream; import java.io.ByteArrayOutputStream; import java.lang.Byte; import org.apache.hadoop.io.IntWritable; import org.apache.hadoop.io.IOUtils; import org.apache.hadoop.util.StringUtils; public class TestWritable extends IntWritable { public static byte[] serialize(IntWritable writable) throws Exception { ByteArrayOutputStream out = new ByteArrayOutputStream(); DataOutputStream dataOut = new DataOutputStream(out); writable.write(dataOut); dataOut.close(); return out.toByteArray(); } public static void main(String[] args) throws Exception { IntWritable i = new IntWritable(); i.set(8); System.out.println(i.get()); byte[] bytes = serialize(i); System.out.println(bytes.toString().length()); System.out.println(StringUtils.byteToHexString(bytes)); } }