Using GeoTools, how should a shapefile be read and written such that it is as identical as possible (idempotent) to the input file, i.e. the schema, projection and any other metadata is unchanged?

My end goal is to read a shapefile and apply some minimal changes to it, but this seems like a good starting point.

I'm not necessarily interested in a working code snippet. A list of things to keep in mind when re-creating a shapefile would be more than enough.

  • 1
    Questions seeking help to debug/write/improve code must include the desired behavior, a specific problem or error and the shortest code necessary to reproduce it in the question itself. Providing a clear problem statement and evidence of a code attempt will help others to help you. – Ian Turton Jun 8 '16 at 10:21
  • Added a working example of what I had in mind. – Martin Valgur Jun 8 '16 at 14:08

Here's the solution to create a shapefile that is identical to the input. I assume this is correct, but I'm not 100% certain.

File inFile = new File("in.shp");
File outFile = new File("out.shp");

// Read
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();

// Write
ShapefileDataStoreFactory dataStoreFactory =
        new ShapefileDataStoreFactory();
ShapefileDataStore newDataStore =
        (ShapefileDataStore) dataStoreFactory.createNewDataStore(
        Collections.singletonMap("url", outFile.toURI().toURL()));

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

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


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