项目需要对多个shp文件做合并和求交,而geotools常用的几何工具都是针对单个Geometry的,若手动获取shp里的要素集合并遍历每个要素的geometry,可能效率会很低,所以找到了geotools的process工具,测试了一下
合并两个shp文件
用到的工具
UnionFeatureCollection
需要的依赖
<dependency>
<groupId>org.geotools</groupId>
<artifactId>gt-process</artifactId>
<version>${
geotools.version}</version>
</dependency>
<dependency>
<groupId>org.geotools</groupId>
<artifactId>gt-process-feature</artifactId>
<version>${
geotools.version}</version>
</dependency>
代码
// ShapeFileReaderUtils和ShapeFileWriterUtils是自己定义的,内容见下面地址
// https://blog.youkuaiyun.com/Neuromancerr/article/details/119981046
public static void mergeTest() throws Exception {
// 待合并的两个文件地址
String pathHead = "D:\\mapresources\\test\\";
String file1 = pathHead + "test1.shp";
String file2 = pathHead + "test2.shp";
// 获取要素集
ContentFeatureCollection features1 = ShapeFileReaderUtils.getFeatureSourceFromShapeFile(file1).getFeatures();
ContentFeatureCollection features2 = ShapeFileReaderUtils.getFeatureSourceFromShapeFile(file2).getFeatures();
// 定义输出路径
String outPut = "D:\\mapresources\\test\\testOut.shp";
// 初始化
UnionFeatureCollection collection2 = new UnionFeatureCollection();
// 执行合并
SimpleFeatureCollection result = collection2.execute(
features1,
features2
);
// 输出结果生成shp文件
ShapeFileWriterUtils.buildShp(result, outPut)

本文介绍了使用Geotools库的UnionFeatureCollection和IntersectionFeatureCollection进行Shapefile数据合并和求交的操作,探讨了如何解决性能瓶颈和结果不正确的问题,以及一种低效但可行的笨拙方法。
最低0.47元/天 解锁文章
3402





