java解析shp文件

使用geotools 解析shp文件 不适用java11

jar包在maven仓库是没有的 所以使用jar打包到本地的方式 

jar包在我的资源里面有可以下载

pom文件


        <!-- 解析shp文件-->
 <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-lang3</artifactId>
            <version>3.12.0</version>
        </dependency>
        <dependency>
            <groupId>com.vividsolutions</groupId>
            <artifactId>jts</artifactId>
            <version>1.11</version>
        </dependency>
        <dependency>
            <groupId>com.googlecode.json-simple</groupId>
            <artifactId>json-simple</artifactId>
            <version>1.1</version>
        </dependency>

        <!--解析shp文件用的jar包,本地jar包-->
        <dependency>
            <groupId>org.opengis</groupId>
            <artifactId>geoapi</artifactId>
            <version>2.3-M1</version>
        </dependency>
        <dependency>
            <groupId>org.opengis</groupId>
            <artifactId>geoapi-pending</artifactId>
            <version>2.3-M1</version>
        </dependency>
        <dependency>
            <groupId>org.geotools</groupId>
            <artifactId>gt-api</artifactId>
            <version>2.7-M0</version>
        </dependency>
        <dependency>
            <groupId>org.geotools</groupId>
            <artifactId>gt-geojson</artifactId>
            <version>2.7-M0</version>
        </dependency>
        <dependency>
            <groupId>org.geotools</groupId>
            <artifactId>gt-main</artifactId>
            <version>2.7-M0</version>
        </dependency>
        <dependency>
            <groupId>org.geotools</groupId>
            <artifactId>gt-metadata</artifactId>
            <version>2.7-M0</version>
        </dependency>
        <dependency>
            <groupId>org.geotools</groupId>
            <artifactId>gt-shapefile</artifactId>
            <version>2.7-M0</version>
        </dependency>

解析的代码



/**
     * 导入shp文件解析
     * @param files 文件
     * @return 解析结果
     */
    
    public AjaxResult importShp(MultipartFile[] files){
        long start=System.currentTimeMillis();
        String fileId=UUID.randomUUID().toString();
        File shapeFile=null;
        File shxFile=null;
        try{
            if(null==files||files.length<2){
                return AjaxResult.error("文件不能为空并且必须包含.shp和对应的.shx文件");
            }
            if(!files[0].getOriginalFilename().contains(".shp")&&!files[0].getOriginalFilename().contains(".shx")){
                return AjaxResult.error("文件类型必须是.shp和对应的.shx文件");
            }
            if(!files[1].getOriginalFilename().contains(".shp")&&!files[1].getOriginalFilename().contains(".shx")){
                return AjaxResult.error("文件类型必须是.shp和对应的.shx文件");
            }
            //转换成file文件 然后进行解析
            for (MultipartFile img : files) {
                String fileName =img.getOriginalFilename();
                if (fileName.contains(".shp")) {
                    fileName =fileId+".shp";
                    File file = new File(rsConfig.getThumbnailTempUrl(),fileName);
                    if (!file.exists()){
                        img.transferTo(file);
                    }else{
                        file.delete();
                        img.transferTo(file);
                    }
                    shapeFile=file;
                }else if(fileName.contains(".shx")){
                    fileName =fileId+".shx";
                    File file = new File(rsConfig.getThumbnailTempUrl(),fileName);
                    if (!file.exists()){
                        img.transferTo(file);
                    }else{
                        file.delete();
                        img.transferTo(file);
                    }
                    shxFile=file;
                }

            }
            ShapefileDataStore store = new ShapefileDataStore(shapeFile.toURI().toURL());
            //设置编码
            Charset charset = Charset.forName("GBK");
            store.setStringCharset(charset);
            SimpleFeatureSource sfSource = store.getFeatureSource();
            SimpleFeatureIterator sfIter = sfSource.getFeatures().features();
            // 从ShapeFile文件中遍历每一个Feature,然后将Feature转为GeoJSON字符串
            List<String> pointList=new ArrayList<>();
            while (sfIter.hasNext()) {
                SimpleFeature feature = sfIter.next();
                // Feature转GeoJSON
                FeatureJSON fjson = new FeatureJSON();
                StringWriter writer = new StringWriter();
                fjson.writeFeature(feature, writer);
                String pointJson = writer.toString();
                if(StringUtils.isNotEmpty(pointJson)){
                    //解析出来的文件有问题 自己处理下
                    pointJson=pointJson.replace(":}",":{}");
                }
                log.debug("pointJson===== >>>>{} " ,pointJson);
                getPoints(pointJson,pointList);
            }
            log.info("importShp.delay={}",(System.currentTimeMillis() - start));
            //转换格式 返回给前端
            return AjaxResult.success("成功",pointList);
        }catch (Exception e){
            log.error("importShp.error={}",e);
        } finally {
            //删除临时文件
            if(null!=shapeFile&&shapeFile.exists()){
                shapeFile.delete();
            }
            if(null!=shxFile&&shxFile.exists()){
                shxFile.delete();
            }
        }
        return AjaxResult.error("解析失败");
    }

   /**
     * 解析组装数据
     * @param json 数据
     * @param pointList 经纬度信息
     */
    public void getPoints(String json,List<String> pointList){
        JSONObject jsonObject=JSONObject.parseObject(json);
        JSONObject geometry=jsonObject.getJSONObject("geometry");
        String type=geometry.getString("type");
        JSONArray coordinates=geometry.getJSONArray("coordinates");
        if("MultiPolygon".equals(type)) {//多个
            for (int k = 0; k < coordinates.size(); k++) {
                List<String> points=new ArrayList<>();
                JSONArray tempArray = coordinates.getJSONArray(k).getJSONArray(0);
                for (int j = 0; j < tempArray.size(); j++) {
                    JSONArray array = tempArray.getJSONArray(j);
                    String point=array.getDoubleValue(0)+","+array.getDoubleValue(1);
                    points.add(point);
                }
                String pointTem=points.stream().collect(Collectors.joining(";"));
                pointList.add(pointTem);
            }
        }else if("Polygon".equals(type)) {//单个
            JSONArray tempArray = coordinates.getJSONArray(0);
            List<String> points=new ArrayList<>();
            for (int j = 0; j < tempArray.size(); j++) {
                JSONArray array = tempArray.getJSONArray(j);
                String point=array.getDoubleValue(0)+","+array.getDoubleValue(1);
                points.add(point);
            }
            String pointTem=points.stream().collect(Collectors.joining(";"));
            pointList.add(pointTem);
        }
    }

线上环境java11  所以要变更使用的jar信息

 Upgrade — GeoTools 28-SNAPSHOT User Guide

IntelliJ Quickstart — GeoTools 28-SNAPSHOT User Guide

从此处下载所需的对应的版本的jar 包

Nexus Repository Manager

Nexus Repository Manager

 

  <!-- 解析shp文件-->
 <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-lang3</artifactId>
            <version>3.12.0</version>
        </dependency>

        <dependency>
            <groupId>com.vividsolutions</groupId>
            <artifactId>jts</artifactId>
            <version>1.13</version>
        </dependency>
        <dependency>
            <groupId>com.googlecode.json-simple</groupId>
            <artifactId>json-simple</artifactId>
            <version>1.1.1</version>
        </dependency>

        <dependency>
            <groupId>org.locationtech.jts</groupId>
            <artifactId>jts-core</artifactId>
            <version>1.16.1</version>
        </dependency>

        <!--解析shp文件用的jar包,本地jar包-->
        <dependency>
            <groupId>org.opengis</groupId>
            <artifactId>geoapi</artifactId>
            <version>2.3-M3</version>
        </dependency>
        <dependency>
            <groupId>org.opengis</groupId>
            <artifactId>geoapi-pending</artifactId>
            <version>2.3-M3</version>
        </dependency>
        <dependency>
            <groupId>org.geotools</groupId>
            <artifactId>gt-geojson</artifactId>
            <version>21.5</version>
        </dependency>
        <dependency>
            <groupId>org.geotools</groupId>
            <artifactId>gt-main</artifactId>
            <version>21.5</version>
        </dependency>
        <dependency>
            <groupId>org.geotools</groupId>
            <artifactId>gt-metadata</artifactId>
            <version>21.5</version>
        </dependency>
        <dependency>
            <groupId>org.geotools</groupId>
            <artifactId>gt-shapefile</artifactId>
            <version>21.5</version>
        </dependency>

<dependency>
            <groupId>org.geotools</groupId>
            <artifactId>gt-opengis</artifactId>
            <version>21.5</version>
        </dependency>
<dependency>
            <groupId>org.geotools</groupId>
            <artifactId>gt-referencing</artifactId>
            <version>21.5</version>
        </dependency>
  public static void main(String[] args) throws Exception {
      File shapeFile = new File("D:\\","single.shp");
      ShapefileDataStore store = new ShapefileDataStore(shapeFile.toURI().toURL());
      //设置编码
      Charset charset = Charset.forName("GBK");
      store.setCharset(charset);
      SimpleFeatureSource sfSource = store.getFeatureSource();
      SimpleFeatureIterator sfIter = sfSource.getFeatures().features();
      // 从ShapeFile文件中遍历每一个Feature,然后将Feature转为GeoJSON字符串
      List<String> pointList=new ArrayList<>();
      while (sfIter.hasNext()) {
          SimpleFeature feature = sfIter.next();
          // Feature转GeoJSON
          FeatureJSON fjson = new FeatureJSON();
          StringWriter writer = new StringWriter();
          fjson.writeFeature(feature, writer);
          String pointJson = writer.toString();
          System.out.println(pointJson);
      }
  }

  • 4
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 4
    评论
解析 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。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值