Database Reference
In-Depth Information
ByteArrayOutputStream out
=
new
ByteArrayOutputStream
();
DataOutputStream dataOut
=
new
DataOutputStream
(
out
);
writable
.
write
(
dataOut
);
dataOut
.
close
();
return
out
.
toByteArray
();
}
An integer is written using four bytes (as we see using JUnit 4 assertions):
byte
[]
bytes
=
serialize
(
writable
);
assertThat
(
bytes
.
length
,
is
(
4
));
The bytes are written in big-endian order (so the most significant byte is written to the
stream first, which is dictated by the
java.io.DataOutput
interface), and we can see
their hexadecimal representation by using a method on Hadoop's
StringUtils
:
assertThat
(
StringUtils
.
byteToHexString
(
bytes
),
is
(
"000000a3"
));
Let's try deserialization. Again, we create a helper method to read a
Writable
object
from a byte array:
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
;
}
We construct a new, value-less
IntWritable
, and then call
deserialize()
to read
from the output data that we just wrote. Then we check that its value, retrieved using the
get()
method, is the original value, 163:
IntWritable newWritable
=
new
IntWritable
();
deserialize
(
newWritable
,
bytes
);
assertThat
(
newWritable
.
get
(),
is
(
163
));
WritableComparable and comparators
IntWritable
implements the
WritableComparable
interface, which is just a
subinterface of the
Writable
and
java.lang.Comparable
interfaces:
package
org
.
apache
.
hadoop
.
io
;
public interface
WritableComparable
<
T
>
extends
Writable
,