4

I'm accessing exiting shapefile with:

File file = new File("file_name.shp");
Map<String, Object> map = new HashMap<String, Object>();
map.put("url", file.toURI().toURL());
DataStore dataStore = DataStoreFinder.getDataStore(map);

or directly the associated dbf:

FileDataStore myData = FileDataStoreFinder.getDataStore(file);
SimpleFeatureSource source = myData.getFeatureSource();
SimpleFeatureType schema = source.getSchema();

but in both ways I don't know how to proceed in order to rename the column (attribute) names. I haven't found solution in the Shapefile Plugin documentation.

1 Answer 1

5

You need to create a new FeatureType (schema) for your output DataStore with the new column names and then copy the features to the new type and write them out.

Something like this will do it:

DataStore inputDataStore = DataStoreFinder.getDataStore(Collections.singletonMap("url", inFile.toURI().toURL()));

    String inputTypeName = inputDataStore.getTypeNames()[0];
    SimpleFeatureType inputType = inputDataStore.getSchema(inputTypeName);
    FeatureSource<SimpleFeatureType, SimpleFeature> source = inputDataStore.getFeatureSource(inputTypeName);

    FeatureCollection<SimpleFeatureType, SimpleFeature> inputFeatureCollection = source.getFeatures();

    // Create new schema

    SimpleFeatureTypeBuilder builder = new SimpleFeatureTypeBuilder();
    builder.add(inputType.getGeometryDescriptor()); // first the_geom
    builder.add(inputType.getDescriptor("STATE_NAME"));
    builder.setName("Output");
    SimpleFeatureType outType = builder.buildFeatureType();

    /*
     * Alternative method
     * try { outType = DataUtilities.createSubType(inputType, new String[]{"the_geom","STATE_NAME"}); } catch (SchemaException e) {}
     */
    // Copy
    ArrayList<SimpleFeature> list = new ArrayList<>();
    try (SimpleFeatureIterator itr = (SimpleFeatureIterator) inputFeatureCollection.features()) {
      while (itr.hasNext()) {
        SimpleFeature f = DataUtilities.reType(outType, itr.next());
        list.add(f);
      }
    }
    FeatureCollection<SimpleFeatureType, SimpleFeature> outputFeatureCollection = DataUtilities.collection(list);
    // Write
    ShapefileDataStoreFactory dataStoreFactory = new ShapefileDataStoreFactory();
    ShapefileDataStore newDataStore = (ShapefileDataStore) dataStoreFactory
        .createNewDataStore(Collections.singletonMap("url", outFile.toURI().toURL()));

    newDataStore.createSchema(outType);
    String typeName = newDataStore.getTypeNames()[0];

    SimpleFeatureStore featureStore = (SimpleFeatureStore) newDataStore.getFeatureSource(typeName);

    featureStore.addFeatures(outputFeatureCollection);
  }

Your Answer

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

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