geotools工具解析shape文件

135 阅读1分钟

1.解析shape文件只获取图形(geometry)

public Map<String,Object> readShape(String path)throws Exception{
        Map<String, Object> map = new HashMap<>();
        ShapefileDataStore store =new ShapefileDataStore(new File(path).toURI().toURL());
        store.setCharset(StandardCharsets.UTF_8);
        FeatureCollection<SimpleFeatureType,SimpleFeature> features = store.getFeatureSource().getFeatures();
        Arrays.stream(features.toArray()).forEach(s->{
            SimpleFeature feature= (SimpleFeature) s;
            GeometryAttribute geometryProperty = feature.getDefaultGeometryProperty();
            System.out.println(geometryProperty.getValue());
//            feature.getProperties().forEach(p->{
//                String name = p.getName().toString();
//                String value = p.getValue().toString();
//                System.out.println(name+"="+value);
//            });
        });
        return map;
}

store.setCharset(StandardCharsets.UTF_8); 设置编码格式用于乱码

2.解析shape文件获取所有字段

ShapefileDataStore store =new ShapefileDataStore(new File(path).toURI().toURL());
        store.setCharset(StandardCharsets.UTF_8);
        FeatureCollection<SimpleFeatureType,SimpleFeature> features = store.getFeatureSource().getFeatures();
        Arrays.stream(features.toArray()).forEach(s->{
            SimpleFeature feature= (SimpleFeature) s;
            feature.getProperties().forEach(p->{
                //字段
                String field = p.getName().toString();
                //值
                String value = p.getValue().toString();
                System.out.println(field+"="+value);
            });
        });

3.获取字段类型

SimpleFeature feature= (SimpleFeature) s;  
feature.getProperties().forEach(p->{  
    String type= p.getType().getName().toString();  
    System.out.println(type);  
});

通过p.getType().getName().toString(); 来获取字段类型