How to create and populate shp file with GeoTools API

我的未来我决定 提交于 2019-12-11 15:59:39

问题


I need to create an empty shape file and populate it with data from my java colletion. Can someone show me an example of how to achieve this? Thanks in advance.


回答1:


For full details please see the CSV to Shapefile tutorial.

Basically you need to define the Shapefiles columns in a SimpleFeatureType object, the easiest way to do this is to use a SimpleFeatureTypeBuilder. Here is generated from directly using a utility method to save time.

    final SimpleFeatureType TYPE = 
        DataUtilities.createType("Location",
            "location:Point:srid=4326," + // <- the geometry attribute: Point type
                    "name:String," + // <- a String attribute
                    "number:Integer" // a number attribute
    );

Now, you can create the Shapefile:

    /*
     * Get an output file name and create the new shapefile
     */
    File newFile = getNewShapeFile(file);

    ShapefileDataStoreFactory dataStoreFactory = new ShapefileDataStoreFactory();

    Map<String, Serializable> params = new HashMap<String, Serializable>();
    params.put("url", newFile.toURI().toURL());
    params.put("create spatial index", Boolean.TRUE);

    ShapefileDataStore newDataStore = (ShapefileDataStore) dataStoreFactory.createNewDataStore(params);
    newDataStore.createSchema(TYPE);

    /*
     * You can comment out this line if you are using the createFeatureType method (at end of
     * class file) rather than DataUtilities.createType
     */
    newDataStore.forceSchemaCRS(DefaultGeographicCRS.WGS84);

And, finally write the collection of Features to it:

    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);
    }


来源:https://stackoverflow.com/questions/50334453/how-to-create-and-populate-shp-file-with-geotools-api

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!