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.

asked Oct 27, 2016 at 7:10

1 Answer 1

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);
 }
}
answered Oct 27, 2016 at 7:51

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.