场景
有一个文件夹,里面有若干个shp文件和子文件夹,子文件夹中包含还包含shp或者子文件夹...
需要一个util把全部的shp都提取出来,提取空间信息(或者外加属性信息,或者可以提取指定的属性信息)。
实现思路
1. 空间信息的工具用geotools API
2. 循环读取shp文件夹下的shp文件的绝对路径出来
3. 增加个过滤的条件,用于提取只希望提取的属性值出来
实现
依赖
<dependency>
<groupId>org.geotools</groupId>
<artifactId>gt-shapefile</artifactId>
<version>26.4</version>
</dependency>
<dependency>
<artifactId>guava</artifactId>
<groupId>com.google.guava</groupId>
<version>28.2-jre</version>
</dependency>
<dependency>
<groupId>org.geotools</groupId>
<artifactId>gt-cql</artifactId>
<version>26.4</version>
</dependency>
<dependency>
<groupId>org.geotools</groupId>
<artifactId>gt-main</artifactId>
<version>26.4</version>
</dependency>
代码
import org.apache.commons.lang3.StringUtils;
import org.geotools.data.DataStore;
import org.geotools.data.DataStoreFinder;
import org.geotools.data.FeatureSource;
import org.geotools.data.shapefile.ShapefileDataStore;
import org.geotools.data.store.ContentFeatureCollection;
import org.geotools.data.store.ContentFeatureSource;
import org.geotools.feature.FeatureCollection;
import org.geotools.feature.FeatureIterator;
import org.geotools.geometry.jts.ReferencedEnvelope;
import org.geotools.referencing.CRS;
import org.locationtech.jts.geom.Envelope;
import org.locationtech.jts.geom.Geometry;
import org.opengis.feature.GeometryAttribute;
import org.opengis.feature.Property;
import org.opengis.feature.simple.SimpleFeature;
import org.opengis.feature.simple.SimpleFeatureType;
import org.opengis.filter.Filter;
import org.opengis.referencing.crs.CoordinateReferenceSystem;
import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.*;
import java.util.stream.Collectors;
public class ShapeFileUtil {
/**
* convert shpFileType to db field type
* 备注:目前arcgis的字段类型有:短整型 长整型 浮点型 双精度 文本 日期
*
* @param value
* @return
*/
public static String convertShpFieldType2H2GISOrPG(Class value) throws Exception {
if (value == String.class) {//文本
return "varchar";
}
if (value == Integer.class) {//短整型
return "int";
}
if (value == Long.class) {//长整型
return "bigint";
}
if (value == Double.class || value == Float.class) {//浮点型 双精度 保留精度,比如在金币上运算更安全
return "numeric";
}
if (value == Date.class) {
return "TIMESTAMP WITH TIME ZONE ";//日期, 使用包含时区的来处理
}
if (Geometry.class.isAssignableFrom(value)) {
return "geometry";
}
//除了上述,真不知道还会有啥了。除非arcgis的shp又增加了新类型?!那无能为力了,抛出异常吧
throw new Exception("不支持的类型!" + value.getName());
//

文章提供了一个Java实现,利用Geotools库遍历目录中的Shapefile文件,提取其空间信息和(可选)特定属性信息。代码示例展示了如何读取Shapefile的bbox,以及如何根据条件过滤属性字段。此外,还提供了将Shapefile字段类型转换为数据库字段类型的辅助方法。
最低0.47元/天 解锁文章
1553

被折叠的 条评论
为什么被折叠?



