geotools

Geotools: error while creating SimpleFeatureWriter from ShapefileDataStore


I am trying to write a shapefile:

File shapefile = new File(....);
Map<String, Serializable> map = new HashMap();
map.put("url", shapefile.toURI().toURL());
SimpleFeatureTypeBuilder builder = new SimpleFeatureTypeBuilder();
builder.setName("MultiPolygonFeatureType");
CoordinateReferenceSystem crs = DefaultGeographicCRS.WGS84
builder.setCRS(crs);
builder.add("location", MultiPolygon.class);
builder.add("name", String.class);
SimpleFeatureType featureType = builder.buildFeatureType();

ShapefileDataStoreFactory factory = new ShapefileDataStoreFactory();
ShapefileDataStore dataStore = (ShapefileDataStore) factory.createNewDataStore(map);
dataStore.createSchema(featureType);
SimpleFeatureWriter writer = (SimpleFeatureWriter) 
dataStore.getFeatureWriterAppend(dataStore.getTypeNames()[0], new DefaultTransaction());

But this gives me error:

java.lang.ClassCastException: class org.geotools.data.InProcessLockingManager$1 cannot be cast to class org.geotools.data.simple.SimpleFeatureWriter (org.geotools.data.InProcessLockingManager$1 and org.geotools.data.simple.SimpleFeatureWriter are in unnamed module of loader 'app')

What part am I missing here?


Solution

  • Basically as the error says you can't cast to a SimpleFeatureWriter. So you should do this:

    FeatureWriter<SimpleFeatureType, SimpleFeature> writer = dataStore.getFeatureWriterAppend(dataStore.getTypeNames()[0], new DefaultTransaction());
    

    and as I said in the comment for a shapefile you must call the geometry attribute the_geom:

    builder.add("the_geom", MultiPolygon.class);
    

    With those 2 changes the following code does work:

        File shapefile = new File("/tmp/ian.shp");
        HashMap<String, Serializable> map = new HashMap();
        map.put("url", URLs.fileToUrl(shapefile));
        SimpleFeatureTypeBuilder builder = new SimpleFeatureTypeBuilder();
        builder.setName("MultiPolygonFeatureType");
        CoordinateReferenceSystem crs = DefaultGeographicCRS.WGS84;
        builder.setCRS(crs);
        builder.add("the_geom", MultiPolygon.class);
        builder.add("name", String.class);
        SimpleFeatureType featureType = builder.buildFeatureType();
    
        ShapefileDataStoreFactory factory = new ShapefileDataStoreFactory();
        ShapefileDataStore dataStore = (ShapefileDataStore) factory.createNewDataStore(map);
        dataStore.createSchema(featureType);
        FeatureWriter<SimpleFeatureType, SimpleFeature> writer = dataStore.getFeatureWriterAppend(dataStore.getTypeNames()[0], new DefaultTransaction());