Java Reference
In-Depth Information
for(i=0;i<locations.size(); i++ ) {
Location l = (Location)locations.elementAt(i);
b = l.toBytes();
dos.writeInt(b.length);
dos.write(b);
}
dos.close();
close();
}
catch(Exception ex) {}
}
}
The first change necessary isn't really one for the FCOP: this
LocationStore
uses a
Vector
to store the list of
Location
instances rather than relying on the file for indexed
access. Instead, this change loads all the forecasts into a
Vector
, and each time the
Vector
is changed, it flushes the changes to disk. The constructor creates this
Vector
and then
enumerates the mounted file systems, selecting the first (which likely represents the
internal store) and constructing a GCF-compliant file name that consists of the
file:///
protocol, the name of the internal file system root, and the name of the store. Finally, it
calls
load
to read the records from the file. The
open
and
close
methods open and close
the
FileConnection
, respectively.
The
load
method begins by removing any existing elements in the
Vector
and
then opening the
FileConnection
and then a
DataInputStream
to the file itself. With the
DataInputStream
open, it reads the version of the file (which will always be
1
in the present
implementation) and then loops over the file, reading first the length of a record and then
the record as a collection of bytes and converting each collection to a
Location
instance.
The
save
method works in the reverse, creating a
DataOutputStream
and writing a version
of
1
before iterating over each
Location
, writing first the length and then the binary repre-
sentation of each
Location
. This approach requires only changes to the
LocationStore
class, not the
Location
class, and does not require any changes to the interface.
■
Tip
When in doubt, use the
RecordStore
for data storage like this. It's guaranteed to be on every MIDP-
compliant device, unlike
FileConnection
, which may not be. The example in this section illustrates how to
use the FCOP rather than explain when it should be used.
Integrating the class in Listing 7-4 into the WeatherWidget example is trivial and fol-
lows the same basic changes that I describe in the previous chapter. Because the FCOP
isn't available on all Java ME devices, the WeatherWidget example uses the record store
implementation of the
LocationStore
class.