2

I have a shapefile with an attribute I want to compute programmatically in Java for each feature. I have found a lot of documentation on how to read and create shapefiles with geotools (http://docs.geotools.org/stable/userguide/library/data/shape.html http://osgeo-org.1560.x6.nabble.com/Add-an-attribute-to-all-the-features-of-a-shape-file-td4318371.html), but no documentation on how to modify an attribute.

So far, I am loading the shapefile data into a FeatureCollection, and modifying each feature attribute with:

myFeature.setAttribute("ATTRIBUTE", myAttributeValue);

but these modifications are not stored into the shapefile (only in memory I guess).

Is there a way to make these modification persistent into the shapefile? Maybe there is a more standard and simple way to update feature attribute with geotools. The only thing I would like to avoid is to re-create a new shapefile.

4

The only way to make these changes persistent is to write them out to disk (in any format you like). There is nothing to stop you using the same filename as you read in (if you feel brave) but making a new copy is always safest.

The feature tutorial contains an example of how to write features out.

    /*
     * Write the features to the shapefile
     */
    Transaction transaction = new DefaultTransaction("create");

    String typeName = newDataStore.getTypeNames()[0];
    SimpleFeatureSource featureSource = newDataStore.getFeatureSource(typeName);

    if (featureSource instanceof SimpleFeatureStore) {
        SimpleFeatureStore featureStore = (SimpleFeatureStore) featureSource;

        featureStore.setTransaction(transaction);
        try {
            featureStore.addFeatures(collection);
            transaction.commit();

        } catch (Exception problem) {
            problem.printStackTrace();
            transaction.rollback();

        } finally {
            transaction.close();
        }
        System.exit(0); // success!
    } else {
        System.out.println(typeName + " does not support read/write access");
        System.exit(1);
    }
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.