package com.se.simu.utils;
|
|
import org.geotools.data.DataStore;
|
import org.geotools.data.DataStoreFinder;
|
import org.geotools.data.FeatureSource;
|
import org.geotools.data.shapefile.ShapefileDataStore;
|
import org.geotools.feature.FeatureCollection;
|
import org.geotools.feature.FeatureIterator;
|
import org.locationtech.jts.geom.Geometry;
|
import org.locationtech.jts.io.WKTReader;
|
import org.opengis.feature.Property;
|
import org.opengis.feature.simple.SimpleFeature;
|
import org.opengis.feature.simple.SimpleFeatureType;
|
|
import java.io.File;
|
import java.nio.charset.Charset;
|
import java.util.*;
|
|
public class ShpReadUtils {
|
public static void main(String[] args) throws Exception {
|
readPointShp("D:\\城市内涝\\sem\\管点\\pipeline-point.shp");
|
//readPointShp("D:\\城市内涝\\sem\\管线\\pipeline-conduit.shp");
|
}
|
|
/**
|
* @param url shp文件路径
|
* @return shp解析后的内容
|
* @throws Exception 异常
|
*/
|
public static List<Map<String, Object>> readPointShp(String url) throws Exception {
|
Map<String, Object> map = new HashMap<String, Object>();
|
File file = new File(url);
|
map.put("url", file.toURI().toURL());// 必须是URL类型
|
DataStore dataStore = DataStoreFinder.getDataStore(map);
|
//字符转码,防止中文乱码
|
((ShapefileDataStore) dataStore).setCharset(Charset.forName("utf8"));
|
String typeName = dataStore.getTypeNames()[0];
|
FeatureSource<SimpleFeatureType, SimpleFeature> source = dataStore.getFeatureSource(typeName);
|
FeatureCollection<SimpleFeatureType, SimpleFeature> collection = source.getFeatures();
|
FeatureIterator<SimpleFeature> features = collection.features();
|
List<Map<String, Object>> list = new ArrayList<>();
|
WKTReader reader = new WKTReader();
|
while (features.hasNext()) {
|
// 迭代提取属性
|
SimpleFeature feature = features.next();
|
Iterator<? extends Property> iterator = feature.getValue().iterator();
|
Map<String, Object> objectMap = new HashMap<>();
|
while (iterator.hasNext()) {
|
Property property = iterator.next();
|
if ("the_geom".equals(property.getName().toString())) {
|
Geometry geometry = reader.read(property.getValue().toString());
|
objectMap.put(property.getName().toString(), geometry);
|
} else {
|
objectMap.put(property.getName().toString(), property.getValue());
|
}
|
}
|
list.add(objectMap);
|
}
|
//读取property中的元素并返回
|
return list;
|
}
|
}
|