Java Reference
In-Depth Information
Once you write the record fields, you can obtain an array of bytes from the
ByteArrayOutputStream
by invoking its
toByteArray
instance method, as shown in
Listing 6-2.
Listing 6-2.
Invoking the toByteArray Instance Method
dos.writeUTF(record);
byte[] bytes = baos.toByteArray();
With the byte array in hand, you can add it to the store using the
addStore
method,
as I show you in the “Adding a Record” section later in this chapter. Of course, it's a good
idea to nil out all three (the byte array
bytes
, the
ByteArrayOutputStream
instance, and the
DataOutputStream
instance) once you're done with them, to tell the garbage collector that
the memory they consume may be released. This can be especially helpful on older
devices with a small heap.
Not surprisingly, deserialization is the opposite of serialization. Begin by creating
instances of
ByteArrayInputStream
and
DataInputStream
from the bytes in a record, as
shown in Listing 6-3.
Listing 6-3.
Creating ByteArrayInputStream and DataInputStream
ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
DataInputStream dis = new DataInputStream(bais);
Next, you can use the following methods from the
DataInputStream
one at a time to
read the data you wrote back from the record:
•
read
: Reads an array of bytes from the stream
•
readBoolean
: Reads a
boolean
from the stream
•
readByte
: Reads a single byte from the stream
•
readChar
: Reads a character from the stream as a two-byte value with the high
byte first
•
readChars
: Reads a
String
as a sequence of characters
•
readDouble
: Reads a
long
from the stream as an eight-byte value and converts the
long
to a
double
•
readFloat
: Reads an
int
from the stream as a four-byte value and converts the
int
to a
float