+ /** Write a list of simple features to a shapefile. */
+ public static void saveFeaturesAsShapefile(SimpleFeatureType featureType, List<SimpleFeature> features,
+ Path shpFile) {
+ try {
+ ShapefileDataStoreFactory dataStoreFactory = new ShapefileDataStoreFactory();
+
+ Map<String, Serializable> params = new HashMap<>();
+ params.put("url", shpFile.toUri().toURL());
+
+ params.put("create spatial index", Boolean.TRUE);
+
+ ShapefileDataStore newDataStore = (ShapefileDataStore) dataStoreFactory.createNewDataStore(params);
+ newDataStore.createSchema(featureType);
+
+ String typeName = newDataStore.getTypeNames()[0];
+ SimpleFeatureSource featureSource = newDataStore.getFeatureSource(typeName);
+ if (featureSource instanceof SimpleFeatureStore) {
+ SimpleFeatureStore featureStore = (SimpleFeatureStore) featureSource;
+ SimpleFeatureCollection collection = new ListFeatureCollection(featureType, features);
+
+ try (Transaction transaction = new DefaultTransaction("create")) {
+ try {
+ featureStore.setTransaction(transaction);
+ featureStore.addFeatures(collection);
+ transaction.commit();
+ } catch (Exception problem) {
+ transaction.rollback();
+ throw new RuntimeException("Cannot write shapefile " + shpFile, problem);
+ }
+ }
+ } else {
+ throw new IllegalArgumentException(typeName + " does not support read/write access");
+ }
+ } catch (IOException e) {
+ throw new RuntimeException("Cannot write shapefile " + shpFile, e);
+ }
+ }
+