I want to edit my shapefile by adding a new column "ID" and assign a value to it. I am trying to achieve this using Java Geotools. Here is the snippet code:

 File inFile = new File("/abc".shp");

        System.out.println("********* GEOTOOLS *************");

        System.out.println("********* READ *************");
        Map<String, Object> map = new HashMap<>();
        map.put("url", inFile.toURI().toURL());

        DataStore dataStore = DataStoreFinder.getDataStore(map);
        String typeName = dataStore.getTypeNames()[0];

        FeatureSource<SimpleFeatureType, SimpleFeature> source =
        Filter filter = Filter.INCLUDE; // ECQL.toFilter("BBOX(THE_GEOM, 10,20,30,40)")

    FeatureCollection<SimpleFeatureType, SimpleFeature> collection = source.getFeatures(filter);
    try (FeatureIterator<SimpleFeature> features = collection.features()) {
        while (features.hasNext()) {
            SimpleFeature feature = features.next();

            // Adding new column attribute ID

            feature.setAttribute("id", "ADSAS2132312");

            System.out.print(": ");

// Write the features to the shapefile

System.out.println("********* WRITE *************");

Transaction transaction = new DefaultTransaction("create");

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

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

        try {

        } catch (Exception problem) {

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

I am not able to write the ID column into shapefile. The reading works fine, but not the write part. I don't know much of Java, so its hard for me to figure out. I followed this reference: http://docs.geotools.org/latest/userguide/tutorial/feature/csv2shp.html

  • Id is probably a bad name for an attribute as it is often handled as a special case – Ian Turton Sep 25 '18 at 16:54
  • @IanTurton I could rename it to ID to shapeId or any attribute name. Is there any method which writes the setattribute ? – GeoFresher Sep 25 '18 at 18:59
  • the code where you write the shapefile out is missing from your question – Ian Turton Sep 26 '18 at 7:53
  • @IanTurton I am not sure where to add the new column details in write. I see the example code, but not able to figure out. Does geotools have any explanations for updating the shapefiles or any examples other than reading and writing? – GeoFresher Sep 26 '18 at 14:29