如何使用 GeoTools 创建和填充 shp 文件 API

How to create and populate shp file with GeoTools API

我需要创建一个空的形状文件并用我的 java 收藏中的数据填充它。有人可以告诉我如何实现这一目标的例子吗?提前致谢。

有关完整详细信息,请参阅 CSV to Shapefile tutorial

基本上您需要在 SimpleFeatureType 对象中定义 Shapefile 列,最简单的方法是使用 SimpleFeatureTypeBuilder。这里是直接用实用方法生成的,省时

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

现在,您可以创建 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);

然后,最后将Features的集合写入其中:

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