美文网首页
java读取shp文件

java读取shp文件

作者: 爱的旋转体 | 来源:发表于2024-01-16 15:54 被阅读0次

    添加maven依赖

    <dependency>
                <groupId>org.geotools</groupId>
                <artifactId>gt-shapefile</artifactId>
                <version>27.4</version>
    </dependency>
    

    java代码

    package com.example.demo2;
    
    import lombok.extern.slf4j.Slf4j;
    import org.geotools.data.Query;
    import org.geotools.data.shapefile.ShapefileDataStore;
    import org.geotools.data.simple.SimpleFeatureSource;
    import org.geotools.feature.FeatureCollection;
    import org.geotools.feature.FeatureIterator;
    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;
    
    @Slf4j
    public class Test {
    
        public static void main(String[] args) {
            readShpFile("test.shp");
        }
    
        private static void readShpFile(String filePath){
            try {
                File shpFile = new File(filePath);
                ShapefileDataStore dataStore = new ShapefileDataStore(shpFile.toURI().toURL());
                dataStore.setCharset(Charset.forName("GBK"));//字符集编码取决于实际文件的编码
                SimpleFeatureSource source = dataStore.getFeatureSource();
                FeatureCollection<SimpleFeatureType, SimpleFeature> featureCollection = source.getFeatures(new Query(source.getSchema().getTypeName()));
                try (FeatureIterator<SimpleFeature> features = featureCollection.features()) {
                    while (features.hasNext()) {
                        SimpleFeature feature = features.next();
                        for (Property property : feature.getValue()) {
                            log.info("属性名【{}】 属性值【{}】", property.getName(), property.getValue());
                        }
                        System.out.println();
                    }
                }
            } catch (Exception e) {
                log.error("读取shp文件异常",e);
            }
        }
    }
    

    相关文章

      网友评论

          本文标题:java读取shp文件

          本文链接:https://www.haomeiwen.com/subject/chvkodtx.html