java使用geotools导出shp文件

SHP格式是一种矢量数据格式,用于存储地理信息系统(GIS)数据。
SHP文件由一系列有序的文件组成,我们导出的shp文件包括.shp、.shx、.dbf、.prj以及.fix文件。

  1. .shp(shape)文件:存储矢量地图数据,记录了每个要素的空间位置信息。
  2. .shx(shape index)文件:是索引文件,用于存储.shp文件中要素的位置,加快数据访问速度。
  3. .dbf(dBase)文件:存储矢量数据的属性信息,例如地图上每个点的名称、类型等信息。
  4. .prj(projection)文件:是地图坐标系文件,其中包含地图投影的信息。
  5. .fix文件:fid索引文件

导出shp文件代码实现如下:

	<properties>
        <geotools-version>28.2</geotools-version>
    </properties>
    <dependencies>
        <!-- geotools-->
        <dependency>
            <groupId>org.geotools</groupId>
            <artifactId>gt-main</artifactId>
            <version>${geotools-version}</version>
        </dependency>
        <dependency>
            <groupId>org.geotools</groupId>
            <artifactId>gt-shapefile</artifactId>
            <version>${geotools-version}</version>
        </dependency>
        <dependency>
            <groupId>org.geotools</groupId>
            <artifactId>gt-metadata</artifactId>
            <version>${geotools-version}</version>
        </dependency>
     </dependencies>

    <!-- geotools仓库-->
    <repositories>
        <repository>
            <id>osgeo</id>
            <name>Open Source Geospatial Foundation Repository</name>
            <url>https://repo.osgeo.org/repository/release/</url>
        </repository>
        <repository>
            <id>osgeo-snapshot</id>
            <name>OSGeo Snapshot Repository</name>
            <url>https://repo.osgeo.org/repository/snapshot/</url>
        </repository>
    </repositories>

</project>
public class ExportShp {
	/**
     * 导出shp文件
     *
     * @param dataPropertiesList 属性列表{属性名:属性值}
     * @param fileName           导出shp文件名
     * @param geomType           geometry类型
     */
    private static void exportShp(List<Map<String, Object>> dataPropertiesList, String fileName, String geomType) {
        //创建保存shp文件夹
        String saveFolder = "D:/workspace/vector/vector/exportShp/";
        File dir = new File(saveFolder);
        if (!dir.exists()) {
            FileUtil.mkdir(dir);
        }

        //shp文件路径
        String shpFileName = fileName + ".shp";
        String fileUrl = saveFolder + shpFileName;
        File file = new File(fileUrl);

        FeatureWriter<SimpleFeatureType, SimpleFeature> writer = null;
        ShapefileDataStore ds = null;
        try {
            Map<String, Serializable> params = new HashMap<>();
            params.put(ShapefileDataStoreFactory.URLP.key, file.toURI().toURL());
            ds = (ShapefileDataStore) new ShapefileDataStoreFactory().createNewDataStore(params);

            //定义图形信息和属性信息
            SimpleFeatureTypeBuilder tb = new SimpleFeatureTypeBuilder();
            //设置坐标系
            CoordinateReferenceSystem crs84 = CRS.decode("EPSG:4326", true);
            tb.setCRS(crs84);
            //设置文件名
            tb.setName(fileName);

            //定义导出shp文件地块属性名称
            String geomProperty = "the_geom";
            String idProperty = "ID";
            String nameProperty = "name";
            String descriptionProperty = "desc";

            //设置图形类型
            if ("Polygon".equals(geomType)) {
                tb.add(geomProperty, Polygon.class);
            } else if ("MultiPolygon".equals(geomType)) {
                tb.add(geomProperty, MultiPolygon.class);
            } else if ("Point".equals(geomType)) {
                tb.add(geomProperty, Point.class);
            } else if ("MultiPoint".equals(geomType)) {
                tb.add(geomProperty, MultiPoint.class);
            } else if ("LineString".equals(geomType)) {
                tb.add(geomProperty, LineString.class);
            } else if ("MultiLineString".equals(geomType)) {
                tb.add(geomProperty, MultiLineString.class);
            } else {
                throw new BizIllegalArgumentException("Geometry中没有该类型:" + geomType);
            }
            //设置对应属性类型
            tb.add(idProperty, String.class);
            tb.add(nameProperty, String.class);
            tb.add(descriptionProperty, String.class);

            //设置默认geometry
            tb.setDefaultGeometry(geomProperty);
            //创建
            ds.createSchema(tb.buildFeatureType());
            ds.setCharset(StandardCharsets.UTF_8);

            //设置Writer
            writer = ds.getFeatureWriter(ds.getTypeNames()[0],
                    Transaction.AUTO_COMMIT);
            SimpleFeature feature;
            for (Map<String, Object> map : dataPropertiesList) {
                feature = writer.next();
                //属性赋值  geometry要赋值wkt格式的
                feature.setAttribute(geomProperty, new WKTReader().read((MapUtil.getStr(map, "geometry"))));
                feature.setAttribute(idProperty, MapUtil.getStr(map, idProperty));
                feature.setAttribute(nameProperty, MapUtil.getStr(map, "名称"));
                String description = MapUtil.getStr(map, "描述");
                if (CharSequenceUtil.isNotBlank(description)) {
                    feature.setAttribute(descriptionProperty, description);
                }
            }
            writer.write();
        } catch (IOException | FactoryException | ParseException e) {
            e.printStackTrace();
        } finally {
            //关闭相关流
            try {
                if (writer != null) {
                    writer.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            if (ds != null) {
                ds.dispose();
            }
        }

    }

    public static void main(String[] args) {
        List<Map<String,Object>> propertyList = new ArrayList<>();
        for (int i = 0; i < 3; i++) {
            Map<String,Object> map = new HashMap<>();
            map.put("ID", i);
            map.put("名称", "test" + i);
            map.put("描述", "测试shp导出" + i);
            map.put("geometry", "MULTILINESTRING ((114.0888763800001 22.549298400000055, 114.0897166200001 22.54931240800005, 114.09006708000004 22.549318250000056, 114.09104754000009 22.549328150000065))");
            propertyList.add(map);
        }
        exportShp(propertyList, "test", "MultiLineString");
    }
}

导出后文件如下:
在这里插入图片描述

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 8
    评论
可以使用Geotools库来读写shp文件。下面是一个简单的示例代码,可以读取shp文件并打印出其属性表信息: ```java import java.io.File; import java.io.IOException; import org.geotools.data.DataStore; import org.geotools.data.DataStoreFinder; import org.geotools.data.simple.SimpleFeatureCollection; import org.geotools.data.simple.SimpleFeatureIterator; import org.opengis.feature.simple.SimpleFeature; import org.opengis.feature.simple.SimpleFeatureType; public class ShpFileReader { public static void main(String[] args) throws IOException { // 读取shp文件 File file = new File("path/to/shapefile.shp"); DataStore dataStore = DataStoreFinder.getDataStore(file); String typeName = dataStore.getTypeNames()[0]; SimpleFeatureType schema = dataStore.getSchema(typeName); // 获取属性表信息 System.out.println("Feature Type: " + typeName); System.out.println("Number of attributes: " + schema.getAttributeCount()); System.out.println("Attributes: "); for (int i = 0; i < schema.getAttributeCount(); i++) { System.out.println(schema.getAttributeDescriptors().get(i).getName()); } // 获取要素信息 SimpleFeatureCollection collection = dataStore.getFeatureSource(typeName).getFeatures(); try (SimpleFeatureIterator features = collection.features()) { while (features.hasNext()) { SimpleFeature feature = features.next(); System.out.println(feature.getID() + ": " + feature.getDefaultGeometryProperty().getValue()); } } dataStore.dispose(); } } ``` 需要注意的是,需要在pom.xml中添加geotools依赖: ```xml <dependency> <groupId>org.geotools</groupId> <artifactId>gt-shapefile</artifactId> <version>24.0</version> </dependency> ```

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 8
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值