gis:读取shp文件

java 复制代码
public static void readShpFile(String shpPath) {
    File shpFile = new File(shpPath);
    try {
        // 通过给定的shapefile路径创建ShapefileDataStore对象
        ShapefileDataStore shapefileDataStore = new ShapefileDataStore(shpFile.toURI().toURL());
        
        // 设置编码为UTF-8,以防止属性中的中文字符出现乱码
        shapefileDataStore.setCharset(Charset.forName("UTF-8"));
        
        // 获取FeatureSource对象,用于获取要素集合并进行操作
        FeatureSource featuresource = shapefileDataStore.getFeatureSource(shapefileDataStore.getTypeNames()[0]);
        
        // 读取边界框(bbox)
        ReferencedEnvelope bbox = featuresource.getBounds();
        
        // 读取投影(坐标参考系统)
        CoordinateReferenceSystem crs = featuresource.getSchema().getCoordinateReferenceSystem();
        
        // 获取总要素数量
        int count = featuresource.getCount(Query.ALL);
        
        // 获取要素集合的几何类型(点、线、面等)
        GeometryType geometryType = featuresource.getSchema().getGeometryDescriptor().getType();
        
        // 读取要素集合
        SimpleFeatureCollection simpleFeatureCollection = (SimpleFeatureCollection) featuresource.getFeatures();
        
        // 获取属性字段列表
        List<AttributeDescriptor> attributes = simpleFeatureCollection.getSchema().getAttributeDescriptors();
        
        // 获取要素迭代器
        SimpleFeatureIterator simpleFeatureIterator = simpleFeatureCollection.features();
        
        // 遍历每一个要素
        while(simpleFeatureIterator.hasNext()) {
            SimpleFeature simpleFeature = simpleFeatureIterator.next();
            
            // 使用Java 8的流API遍历每一个属性值,并处理其他业务逻辑
            attributes.stream().forEach((a) -> {
                // 依次读取shapefile中每一个属性的值
                System.out.println(a.getLocalName() + ":" + simpleFeature.getAttribute(a.getLocalName()));
            });
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
    System.out.println("读取完成!");
}

以上代码是一个用于读取 Shapefile 文件的方法。该方法的主要功能包括:

  1. 创建 ShapefileDataStore 对象,用于读取 Shapefile 文件的数据源。
  2. 设置编码为 UTF-8 避免属性中的中文字符乱码。
  3. 获取 FeatureSource 对象,用于获取要素集合和元数据。
  4. 读取边界框(bbox)和投影(坐标参考系统)信息。
  5. 获取要素集合的总数量和几何类型。
  6. 读取要素集合,并获取属性字段列表。
  7. 遍历每一个要素,并打印每个属性字段的值。
    最后,输出读取完成的提示信息。

这段代码提供了一个简单的方式来读取 Shapefile 文件,并获取其中要素和属性的信息。你可以根据需要进一步处理和使用这些数据。

相关推荐
Ws_1 小时前
C#学习 Day2
开发语言·学习·c#
杰克尼2 小时前
天机学堂复习总结(day03-day04)
java·开发语言·redis·elasticsearch·spring cloud
x***r1512 小时前
jdk-11.0.16.1_windows使用步骤详解(附JDK 11环境变量配置与验证教程)
java·开发语言·windows
luck_bor3 小时前
File类&递归作业
java·开发语言
努力努力再努力wz7 小时前
【Qt入门系列】:按钮组件全解析:从 QAbstractButton 到快捷键事件、单选与复选机制
c语言·开发语言·数据结构·c++·git·qt·github
skywalk81637 小时前
言知(Yanzhi)系统提升建议报告和完工报告 by AutoCoder
开发语言·编程
yunn_7 小时前
单例模式两种实现方法
开发语言·c++·单例模式
我材不敲代码7 小时前
Python基础:列表详解、增删改查及常用高阶操作
开发语言·windows·python
AI玫瑰助手8 小时前
Python运算符:成员运算符(in/not in)的使用场景
开发语言·python·信息可视化
AI人工智能+电脑小能手8 小时前
【大白话说Java面试题 第77题】【Mysql篇】第7题:回表查询与全表扫描的区别?
java·开发语言·数据库·mysql·面试