Java Reference
In-Depth Information
A record itself is just a bag of bytes. The good news is that you're free to implement
any structure you see fit on a record; the bad news is that it's up to you to define a struc-
ture that supports your application and scales well. The MIDP implementation lacks the
serialization support found in
java.io.Serializable
, meaning you need to implement
your own serialization. (The interface defined by
java.io.Serializable
doesn't really fit
the notion of records in the record store, either, because there are no lower-level filter
streams to help with serialization, and the object of record serialization is to serialize to
a bag of bytes rather than an output stream.)
This means that you need to be familiar with Java streams, particularly the
java.io.ByteArrayInputStream
,
java.io.ByteArrayOutputStream
,
java.io.DataInputStream
,
and
java.io.DataOutputStream
classes. The process isn't as daunting as it first appears.
To preserve a record, you first create a
DataOutputStream
and a
ByteArrayOutputStream
,
as shown in Listing 6-1.
Listing 6-1.
Creating a DataOutputStream and a ByteArrayOutputStream
ByteArrayOutputStream baos = new ByteArrayOutputStream();
DataOutputStream dos = new DataOutputStream(baos);
Next, you write the record's fields to the
DataOutputStream
using one or more of the
following methods:
•
write
: Takes an array of bytes, an offset, and a number of bytes to write, and writes
those bytes to the stream
•
writeBoolean
: Writes a
boolean
to the stream
•
writeByte
: Writes a single byte to the stream
•
writeChar
: Writes a character to the stream as a two-byte value with the high byte first
•
writeChars
: Writes a
String
as a sequence of characters
•
writeDouble
: Converts the
double
to a
long
using
doubleToLongBits
and writes the
long
to the stream as an eight-byte value
•
writeFloat
: Converts the
float
to an
int
using
floatToIntBits
and writes the
int
to
the stream as a four-byte value
•
writeInt
: Writes an integer with the high byte first
•
writeLong
: Writes a
long
integer with the high byte first
•
writeShort
: Writes a
short
integer with the high byte first
•
writeUTF
: Writes a
String
using Java-modified UTF-8 encoding (in a machine-
specific way)