Java使用Geotools读取shp文件

1、环境版本

序号类别版本
1JDK1.8
2Junit4.13.1
3Geotools25.4
4Collections3.2.2

2、pom文件编写

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.example</groupId>
    <artifactId>geotools-demo</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>geotools-demo</name>
    <description>geotools-demo</description>
    <properties>
        <java.version>1.8</java.version>
        <geotools.version>25.4</geotools.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.13.1</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>commons-collections</groupId>
            <artifactId>commons-collections</artifactId>
            <version>3.2.2</version>
        </dependency>
        <dependency>
            <groupId>org.geotools</groupId>
            <artifactId>gt-shapefile</artifactId>
            <version>${geotools.version}</version>
        </dependency>
        <dependency>
            <groupId>org.geotools</groupId>
            <artifactId>gt-swing</artifactId>
            <version>${geotools.version}</version>
        </dependency>
    </dependencies>
    <repositories>
        <repository>
            <id>osgeo</id>
            <name>OSGeo Release Repository</name>
            <url>https://repo.osgeo.org/repository/release/</url>
            <snapshots><enabled>false</enabled></snapshots>
            <releases><enabled>true</enabled></releases>
        </repository>
        <repository>
            <id>osgeo-snapshot</id>
            <name>OSGeo Snapshot Repository</name>
            <url>https://repo.osgeo.org/repository/snapshot/</url>
            <snapshots><enabled>true</enabled></snapshots>
            <releases><enabled>false</enabled></releases>
        </repository>
    </repositories>
    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

3、WTK读写工具类

package com.example.geotoolsdemo.utils;

import org.locationtech.jts.geom.Geometry;
import org.locationtech.jts.io.ParseException;
import org.locationtech.jts.io.WKTReader;
import org.locationtech.jts.io.WKTWriter;

/**
 * wktutil
 *
 * @author tree
 * @date 2022/01/21
 */
public class WKTUtil {


    public static String geomToWkt(Geometry geometry) {
        WKTWriter writer = new WKTWriter();
        return writer.write(geometry);
    }

    public static Geometry wktToGeom(String wkt) throws ParseException {
        Geometry geometry = null;
        WKTReader reader = new WKTReader();
        geometry = reader.read(wkt);
        return geometry;
    }

}

4、Shape文件工具类

package com.example.geotoolsdemo.utils;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.geotools.data.*;
import org.geotools.data.shapefile.ShapefileDataStore;
import org.geotools.data.shapefile.ShapefileDataStoreFactory;
import org.geotools.feature.FeatureCollection;
import org.geotools.feature.FeatureIterator;
import org.geotools.feature.simple.SimpleFeatureTypeBuilder;
import org.geotools.referencing.crs.DefaultGeographicCRS;
import org.opengis.feature.Property;
import org.opengis.feature.simple.SimpleFeature;
import org.opengis.feature.simple.SimpleFeatureType;

import java.io.*;
import java.nio.charset.Charset;
import java.util.*;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;


public class ShapeUtil {

    public static final String DEF_GEOM_KEY = "the_geom";

    public static final String DEF_ENCODE = "uft-8";

    /**
     * 读取shape文件,默认编码时utf-8
     * @param shpPath shape文件地址,如:D:\data\tmp\test.shp
     * @return shape文件解析后的数据集合
     */
    public static List<Map<String, Object>> readShp(String shpPath) {
        return readShp(shpPath, DEF_ENCODE);
    }
    /**
     * 读取shape文件
     * @param shpPath shape文件地址,如:D:\data\tmp\test.shp
     * @param encode 文件编码
     * @return shape文件解析后的数据集合
     */
    public static List<Map<String, Object>> readShp(String shpPath, String encode) {
        //申明返回结果
        List<Map<String, Object>> list = new ArrayList<>();
        try {
            if (StringUtils.isEmpty(shpPath)) {
                throw new Exception("shp文件的路径不能为空,shpPath: " + shpPath);
            }

            if (StringUtils.isEmpty(encode)) {
                throw new Exception("shp文件的编码不能为空,encode: " + encode);
            }
            //加载shape文件
            File file = new File(shpPath);
            //ShapefileDataStore sds = new ShapefileDataStore("");
            Map<String, Object> map = new HashMap<>();
            map.put(ShapefileDataStoreFactory.URLP.key, file.toURI().toURL());
            map.put(ShapefileDataStoreFactory.DBFCHARSET.key, Charset.forName(encode));
            //加载数据源
            DataStore ds = DataStoreFinder.getDataStore(map);

            //获取要素源
            FeatureSource<SimpleFeatureType, SimpleFeature> fs = ds.getFeatureSource(ds.getTypeNames()[0]);
            FeatureCollection<SimpleFeatureType, SimpleFeature> collections = fs.getFeatures();
            FeatureIterator<SimpleFeature> features = collections.features();

            //循环获取feature
            while (features.hasNext()) {
                SimpleFeature feature = features.next();

                Map<String, Object> featureMap = new HashMap<>();
                for (Property p : feature.getProperties()) {
                    featureMap.put(p.getName().toString(), p.getValue());
                }

                list.add(featureMap);
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        return list;
    }

}


5、测试类

package com.example.geotoolsdemo;

import com.example.geotoolsdemo.utils.ShapeUtil;
import com.example.geotoolsdemo.utils.WKTUtil;
import org.junit.Test;
import org.locationtech.jts.geom.Geometry;
import org.locationtech.jts.geom.Polygon;
import org.locationtech.jts.io.ParseException;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class GeotoolsDemoApplicationTests {

 	@Test
    public void readShp() {
        String url = "D:\\00testdata\\tmp\\test.shp";

        List<Map<String, Object>> list = ShapeUtil.readShp(url, "utf-8");

        System.out.println(list);
    }
}

6、测试结果

com.intellij.rt.junit.JUnitStarter -ideVersion5 -junit4 com.example.geotoolsdemo.GeotoolsDemoApplicationTests,readShp
[{ATTR4=true, ATTR3=23.5, ATTR2=456, the_geom=MULTIPOLYGON (((116.21278950384274 39.90557982319698, 116.21629305278306 39.905011479365406, 116.21399502548638 39.902612822554126, 116.21106912279264 39.90264172209895, 116.21177234433465 39.90610963061354, 116.21278950384274 39.90557982319698))), ATTR5=, ATTR=这是第1}, {ATTR4=false, ATTR3=23.52, ATTR2=4562, the_geom=MULTIPOLYGON (((113.38185597038 34.54828048706, 113.38224220848 34.548355588913, 113.38249970055 34.548108825684, 113.38237095451 34.54787279129, 113.38208127594 34.547786960602, 113.38185597038 34.54828048706))), ATTR5=null, ATTR=这是第2}]

Process finished with exit code 0

7、Demo源码链接及参考地址

源码链接:https://gitee.com/songzongqiang/geotools-demo

参考地址:https://docs.geotools.org/latest/userguide/library/data/shape.html

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

杉叔

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

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

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

打赏作者

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

抵扣说明:

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

余额充值