java实现shapefile文件的解析

必须的文件:

  • .shp— 图形格式,用于保存元素的几何实体。

  • .shx— 图形索引格式。几何体位置索引,记录每一个几何体在shp文件之中的位置,能够加快向前或向后搜索一个几何体的效率。

  • .dbf— 属性数据格式,以dBase IV的数据表格式存储每个几何形状的属性数据。

其他可选的文件:

  • .prj— 投帧式,用于保存地理坐标系统与投影信息,是一个存储well-known text投影描述符的文本文件。

  • .sbnand.sbx— 几何体的空间索引

  • .fbnand.fbx— 只读的Shapefiles的几何体的空间索引

  • .ainand.aih— 列表中活动字段的属性索引。

  • .ixs— 可读写Shapefile文件的地理编码索引

  • .mxs— 可读写Shapefile文件的地理编码索引(ODB格式)

  • .atx—.dbf文件的属性索引,其文件名格式为shapefile.columnname.atx(ArcGIS 8及之后的版本)

  • .shp.xml— 以XML格式保存元数据。

  • .cpg— 用于描述.dbf文件的代码页,指明其使用的字符编码

将shapefile文件放进一个文件夹

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

方法奉上,该方法可指定要获取的字段

参数filePath为shapefile文件路径,任意文件均可

参数mapping为要查询的字段,key为字段别名,value为查询的字段

public static List<Map<String, Object>> getShpData(String filePath, Map<String, String> mapping) throws IOException {
        File f = new File(filePath);
        ShapefileDataStore shpDataStore = new ShapefileDataStore(f.toURI().toURL());
//        shpDataStore.setCharset(StandardCharsets.UTF_8);
        shpDataStore.setCharset(Charset.forName("GBK"));
        String typeName = shpDataStore.getTypeNames()[0];
        FeatureSource<SimpleFeatureType, SimpleFeature> featureSource = shpDataStore.getFeatureSource(typeName);
        FeatureCollection<SimpleFeatureType, SimpleFeature> features = featureSource.getFeatures();
        List<Map<String, Object>> data = new ArrayList<>();
        try (FeatureIterator<SimpleFeature> itertor = features.features()) {
            while (itertor.hasNext()) {
                SimpleFeature feature = itertor.next();
                Geometry geometry = (Geometry) feature.getDefaultGeometry();
                String json = CoordinateConversion.geometryToGeojson(geometry);
                Map<String, Object> o = new HashMap<>();
                o.put("geom", GsonUtil.GsonToMaps(json));
                for (Map.Entry<String, String> entry : mapping.entrySet()) {
                    String k = entry.getKey();
                    String v = entry.getValue();
                    o.put(k, feature.getAttribute(v));
                }
                data.add(o);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            shpDataStore.dispose();
        }
        return data;
    }

但有的时候我们不知道都有哪些字段,我想获取所有字段,那就参考下面的方法

public static Map<String, List<Map<String, Object>>> readSHP(File SHPFile) throws Exception {

        // 一个数据存储实现,允许从Shapefiles读取和写入
        ShapefileDataStore shpDataStore = null;
        System.out.println();
        shpDataStore = new ShapefileDataStore(SHPFile.toURI().toURL());
        shpDataStore.setCharset(Charset.forName("GBK"));
        // 获取这个数据存储保存的类型名称数组
        // getTypeNames:获取所有地理图层
        String typeName = shpDataStore.getTypeNames()[0];
        // 通过此接口可以引用单个shapefile、数据库表等。与数据存储进行比较和约束
        FeatureSource<SimpleFeatureType, SimpleFeature> featureSource = null;
        featureSource = (FeatureSource<SimpleFeatureType, SimpleFeature>) shpDataStore.getFeatureSource(typeName);
        // 一个用于处理FeatureCollection的实用工具类。提供一个获取FeatureCollection实例的机制
        FeatureCollection<SimpleFeatureType, SimpleFeature> result = featureSource.getFeatures();
        FeatureIterator<SimpleFeature> iterator = result.features();
        // 迭代
        int stop = 0;
        Map<String, List<Map<String, Object>>> map = new HashMap<>();
        List<Map<String, Object>> entity = new ArrayList<>();
        List<Map<String, Object>> datas = new ArrayList<>();
        while (iterator.hasNext()) {
            SimpleFeature feature = iterator.next();
            Collection<Property> p = feature.getProperties();
            Iterator<Property> it = p.iterator();
            // 构建实体
            // 特征里面的属性再迭代,属性里面有字段
            String name;
            Map<String, Object> data = new HashMap<>();
            while (it.hasNext()) {
                Property pro = it.next();
                name = pro.getName().toString();
                if (stop == 0) {
                    Map<String, Object> et = new HashMap<>();
                    PropertyType propertyType = pro.getType();
                    Class cls = propertyType.getBinding();
                    String className = cls.getName();
                    String tName = className.substring(className.lastIndexOf(".") + 1);
                    Filter filter = propertyType.getRestrictions().isEmpty() ? null : propertyType.getRestrictions().get(0);
                    String typeLength = filter != null ? filter.toString() : "0";
                    Pattern pattern = Pattern.compile("[^0-9]");
                    Matcher matcher = pattern.matcher(typeLength);
                    String tLength = matcher.replaceAll("").trim();
                    et.put("name", name);
                    et.put("type", tName);
                    et.put("length", tLength);
                    entity.add(et);
                }
                data.put(name, pro.getValue().toString());
            } // end 里层while
            datas.add(data);
            stop++;
        } // end 最外层 while
        map.put("entity", entity);
        map.put("datas", datas);
        iterator.close();
        return map;
    }

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
解析 shp 格式文件,可以使用 Java 开源库 GeoTools。GeoTools 提供了一套 Java API,用于加载、操作和存储空间数据,包括 shp 文件。 以下是一个简单的示例代码,演示如何使用 GeoTools 解析 shp 文件: ```java import java.io.File; import java.io.IOException; import org.geotools.data.DataStore; import org.geotools.data.DataStoreFinder; import org.geotools.data.FeatureSource; import org.geotools.data.simple.SimpleFeatureIterator; import org.opengis.feature.simple.SimpleFeature; public class ShpParser { public static void main(String[] args) throws IOException { // 指定 shp 文件路径 File file = new File("path/to/your/file.shp"); // 加载 shp 文件 DataStore dataStore = DataStoreFinder.getDataStore( Collections.singletonMap("url", file.toURI().toURL()) ); // 获取 FeatureSource String typeName = dataStore.getTypeNames()[0]; FeatureSource featureSource = dataStore.getFeatureSource(typeName); // 遍历 Feature try (SimpleFeatureIterator iterator = featureSource.getFeatures().features()) { while (iterator.hasNext()) { SimpleFeature feature = iterator.next(); // 处理 Feature System.out.println(feature.getID()); } } // 释放资源 dataStore.dispose(); } } ``` 在这个示例中,我们使用 `DataStoreFinder` 类加载 shp 文件,并获取其 `FeatureSource` 对象。然后,可以使用 `FeatureSource` 对象获取 shp 文件中的所有 Feature,并对其进行遍历和处理。 请注意,为了使用 GeoTools,你需要将以下依赖项添加到你的项目中: ```xml <dependency> <groupId>org.geotools</groupId> <artifactId>gt-shapefile</artifactId> <version>${geotools.version}</version> </dependency> <dependency> <groupId>org.geotools</groupId> <artifactId>gt-epsg-hsql</artifactId> <version>${geotools.version}</version> </dependency> ``` 其中,`${geotools.version}` 是 GeoTools 版本号。你可以在 Maven 中心仓库中查找最新版本的 GeoTools。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

BUG制造者木容

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值