目录
2.读取shapefile要素,并将要素创建要素迭代器,用于后续读取字段属性及几何
GIS开发中shapefile是经常使用的几何数据类型,在开发B/S架构的GIS系统中,经常遇到需要使用java读取shapefile数据的需求。下面介绍基于geotools开源工具读取shapefile的通用工具类,配置好相关jar包后即可使用。
本博客的示例数据及源码下载链接:https://download.csdn.net/download/tylkhx/85488007
一、读取效果
这里准备了一个示例数据,下面是读取效果和源数据情况。
1.读取效果
可以看到字段值及几何图形均读取到了,这里使用了hashMap来存储读取到要素,一条要素对应一个Map对象,通过字段名在Ma中获取相应的字段值,几何图形通过“the_geom”来获取,然后将所有Map对象封装为List返回。效果如下。
2.源数据情况
这里是源数据情况,里面的字段和读取到的成果一 一对应。
二、实现过程
1.打开shapefile数据源
file为shp的路径File对象
Map<String, Object> shpMap = new HashMap<>();
shpMap.put("url", file.toURI().toURL());
ShapefileDataStore shapefileDataStore = (ShapefileDataStore)
DataStoreFinder.getDataStore(shpMap);
2.读取shapefile要素,并将要素创建要素迭代器,用于后续读取字段属性及几何
ContentFeatureSource featureSource = shapefileDataStore.getFeatureSource();
ContentFeatureCollection featureCollection = featureSource.getFeatures();
SimpleFeatureIterator featureIterator = featureCollection.features();
3.读取字段属性及几何
首先对要素进行迭代,获取到单条要素,然后对单条要素的属性进行迭代,获取到字段属性及几何图形,并存储为一个Map。单条要素属性全部迭代完毕后,将Map存储到List中。
while (featureIterator.hasNext()){
Map<String,Object> resMap = new HashMap<String, Object>();
SimpleFeature feature = featureIterator.next();
Iterator<? extends Property> iterator = feature.getValue().iterator();
while (iterator.hasNext()){
Property property = iterator.next();
String name = property.getName().toString();
resMap.put(name,property.getValue());
}
resList.add(resMap);
}
featureIterator.close();
三、完整的核心读取方法
public static List<Map<String,Object>> readShapeFile(File file) throws IOException {
List<Map<String,Object>> resList = new ArrayList<>();
Map<String, Object> shpMap = new HashMap<>();
shpMap.put("url", file.toURI().toURL());
ShapefileDataStore shapefileDataStore = (ShapefileDataStore)
DataStoreFinder.getDataStore(shpMap);
String dbf = FileUtils.getFileName(file.getPath()) + ".dbf";
String dbfCharset = getDbfCharset(dbf);
if (dbfCharset != null && dbfCharset.equals("UTF-8")){
shapefileDataStore.setCharset(Charset.forName("UTF-8"));
}else {
shapefileDataStore.setCharset(Charset.forName("GBK"));
}
ContentFeatureSource featureSource = shapefileDataStore.getFeatureSource();
ContentFeatureCollection featureCollection = featureSource.getFeatures();
SimpleFeatureIterator featureIterator = featureCollection.features();
while (featureIterator.hasNext()){
Map<String,Object> resMap = new HashMap<String, Object>();
SimpleFeature feature = featureIterator.next();
Iterator<? extends Property> iterator = feature.getValue().iterator();
while (iterator.hasNext()){
Property property = iterator.next();
String name = property.getName().toString();
resMap.put(name,property.getValue());
}
resList.add(resMap);
}
featureIterator.close();
return resList;
}
四、使用示例
public static void main(String [] args) throws IOException{
String path = "D:/shp读取/演示shp/演示.shp";
List<Map<String, Object>> list = readShapeFile(path);
int i = 1;
}