张洋洋
2025-01-13 e4041d443700bde9c60777275de5ae7e9dfc7468
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
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;
    }
}