The ilog.views.maps.format.shapefile package
contains the following classes for writing Shapefiles.
The class IlvSHPWriter is used to generate the geometry
and index parts of a Shapefile (
.shp
and
.shx
files), while the IlvDBFWriter is used to write the attribute
file (
.dbf
extension).
Like with feature iterator, writing map features to a Shapefile
consists of writing repeatedly map features using the methods writeFeature and writeAttributes, then call the close method of writers to flush the data and
write the headers.
The IlvSHPWriter class
The
IlvSHPWriter
class manages the writing of geometries to a Shapefile, with the
creation of the Shapefile index that allows direct access to
Shapefile records.
The following example shows how to use this class to write the
contents of a feature iterator to a file
foo.shp
, creating the index file at the same time.
try { IlvSHPWriter shpwriter = new IlvSHPWriter("foo.shp", "foo.shx"); // Loop on features. IlvMapFeature feature = iterator.getNextFeature(); while (feature != null) { shpwriter.writeFeature(feature); feature = iterator.getNextFeature(); } shpwriter.close(); } catch (IOException e) { // Error processing. e.printStackTrace(); }
Note
The Shapefile format defines a header that can be completed only
once all data is written. For this reason, it is mandatory to
call the
close()
method of the shape writer once all data is written, so that the
header is updated.
The IlvDBFWriter and IlvDBFAttributeInfo classes
The IlvDBFWriter and IlvDBFAttributeInfo classes manage the
writing of DBase III+ files (
.dbf
files). These files contain records corresponding to attributes
of geometries contained within a Shapefile.
As
.dbf
files need records with fixed-size fields, it is important to
choose a field size that is large enough to contain all data of a
field, as well as a size small enough not to waste data.
The goal of the class
IlvDBFAttributeInfo
is to complement IlvAttributeInfoProperty for the definition
of record fields.
The following example shows how to write the contents of an
iterator to a set of
.shp
,
.shx
and
.dbf
files:
try { // Create the SHP writer. IlvSHPWriter shpwriter = new IlvSHPWriter("foo.shp", "foo.shx"); // Read the first feature. IlvMapFeature feature = iterator.getNextFeature(); // Create the DBF Writer. IlvDBFAttributeInfo info = new IlvDBFAttributeInfo(feature.getAttributeInfo()); IlvDBFWriter dbfwriter = new IlvDBFWriter(info, "foo.dbf"); // Loop on features. while (feature != null) { shpwriter.writeFeature(feature); dbfwriter.writeAttributes(feature.getAttributes()); feature = iterator.getNextFeature(); } shpwriter.close(); dbfwriter.close(); } catch (IOException e) { // Error processing. e.printStackTrace(); }
Once again, the writers must be closed to
write the headers correctly.