geotools将shp数据存入postgres

一、引入geotools的依赖

引入geotools的方法

<dependency>
            <groupId>org.geotools</groupId>
            <artifactId>gt-shapefile</artifactId>
            <version>27-SNAPSHOT</version>
        </dependency>
        <dependency>
            <groupId>org.geotools.jdbc</groupId>
            <artifactId>gt-jdbc-postgis</artifactId>
            <version>27-SNAPSHOT</version>
        </dependency>

二、代码编写

1、代码如下;

package com.example.forestry.util.geotools;

import org.geotools.data.DataStore;
import org.geotools.data.DataStoreFinder;
import org.geotools.data.FeatureWriter;
import org.geotools.data.Transaction;
import org.geotools.data.shapefile.ShapefileDataStore;
import org.geotools.data.simple.SimpleFeatureCollection;
import org.geotools.data.simple.SimpleFeatureIterator;
import org.geotools.data.simple.SimpleFeatureSource;
import org.geotools.jdbc.JDBCDataStore;
import org.opengis.feature.simple.SimpleFeature;
import org.opengis.feature.simple.SimpleFeatureType;

import java.io.File;
import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.Map;

public class Shp2Pgsql {


    /**
     * 获取数据库连接对象
     *
     * @return
     * @throws Exception
     */
    public JDBCDataStore getDataStore(){

        Map<String, Object> params = new HashMap<>();
        // 必须是字符串 postgis
        params.put("dbtype", "postgis");
        // ip
        params.put("host", "192.168.xx.xx");
        // 端口
        params.put("port", 5432);
        // 数据库模式
        params.put("schema", "public");
        // 数据库名称
        params.put("database", "cim");
        params.put("user", "postgres");
        params.put("passwd", "postgres");

        JDBCDataStore dataStore = null;

        try {
            DataStore ds = DataStoreFinder.getDataStore(params);

            if(ds==null){
                System.out.println("连接postgres失败");
            }else {
                dataStore = (JDBCDataStore) ds;
                System.out.println("连接postgres成功");
            }

        }catch (Exception e) {
            e.printStackTrace();
            System.out.println("连接postres出错");
        }

        return dataStore;
    }


    /**
     * 读取shapefile文件
     *
     * @param file
     * @return
     */
    public SimpleFeatureSource readShp(File file){
        SimpleFeatureSource featureSource = null;

        ShapefileDataStore shpDataStore = null;
        try {
            shpDataStore = new ShapefileDataStore(file.toURL());
            
            //设置编码
            Charset charset = Charset.forName("UTF8");
            shpDataStore.setCharset(charset);
            String tableName = shpDataStore.getTypeNames()[0];
            featureSource = shpDataStore.getFeatureSource(tableName);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            shpDataStore.dispose();
        }
        return featureSource;

    }


    /**
     * 创建表
     *
     * @param ds
     * @param source
     * @return
     */
    public JDBCDataStore createTable(JDBCDataStore ds , SimpleFeatureSource source){
        SimpleFeatureType schema = source.getSchema();

        try {
            ds.createSchema(schema);
        }catch (Exception e){
            e.printStackTrace();
            System.out.println("创建postgres数据表失败");
        }

        return ds;
    }


    /**
     * 将shapefile的数据存入数据表中
     *
     * @param ds
     * @param source
     */
    public void shp2Table(JDBCDataStore ds , SimpleFeatureSource source){
        SimpleFeatureIterator features  = null;

        //表名为shp文件的名字
        String tableName = source.getSchema().getTypeName();

        try {

            FeatureWriter<SimpleFeatureType, SimpleFeature> writer = ds.getFeatureWriter(tableName, Transaction.AUTO_COMMIT);
            SimpleFeatureCollection featureCollection = source.getFeatures();

            //创建图层数据迭代器
            features = featureCollection.features();

            //进行逐行写入
            while (features.hasNext()) {
                try {
                    writer.hasNext();
                    SimpleFeature next = writer.next();
                    SimpleFeature feature = features.next();
                    for (int i = 0; i < feature.getAttributeCount(); i++) {
                        next.setAttribute(i, feature.getAttribute(i));
                    }
                    writer.write();
                } catch (Exception e) {
                    e.printStackTrace();
                    System.out.println("添加数据的方法错误:" + e.toString());
                    continue;
                }
            }
            writer.close();

            System.out.println("导入成功");
        }catch (Exception e){
            e.printStackTrace();
            System.out.println("创建写入条件失败:"+e.toString());
        }finally {
            ds.dispose();
            features.close();
        }

    }


    //进行测试
    public static void main(String[] args) {
        Shp2Pgsql shp2Pgsql = new Shp2Pgsql();

        File file = new File("D:\\data\\shapefile\\tree\\tree.shp");

        Long startTime = System.currentTimeMillis();

        //获取postgres连接对象
        JDBCDataStore dataStore = shp2Pgsql.getDataStore();

        //读取shapefile文件
        SimpleFeatureSource simpleFeatureSource = shp2Pgsql.readShp(file);

        //创建数据表
        JDBCDataStore ds = shp2Pgsql.createTable(dataStore, simpleFeatureSource);

        //进行数据写入
        shp2Pgsql.shp2Table(ds , simpleFeatureSource);

        Long endTime = System.currentTimeMillis();

        Long time = (endTime - startTime)/1000;

        System.out.println("时间为: "+time+" 秒");

    }


}

2、插入速度;我电脑i5-10th的cpu,8G内存,跑49万条数据用了255秒;
在这里插入图片描述

  • 5
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 6
    评论
可以使用Geotools库来读写shp文件。下面是一个简单的示例代码,可以读取shp文件并打印出其属性表信息: ```java import java.io.File; import java.io.IOException; import org.geotools.data.DataStore; import org.geotools.data.DataStoreFinder; import org.geotools.data.simple.SimpleFeatureCollection; import org.geotools.data.simple.SimpleFeatureIterator; import org.opengis.feature.simple.SimpleFeature; import org.opengis.feature.simple.SimpleFeatureType; public class ShpFileReader { public static void main(String[] args) throws IOException { // 读取shp文件 File file = new File("path/to/shapefile.shp"); DataStore dataStore = DataStoreFinder.getDataStore(file); String typeName = dataStore.getTypeNames()[0]; SimpleFeatureType schema = dataStore.getSchema(typeName); // 获取属性表信息 System.out.println("Feature Type: " + typeName); System.out.println("Number of attributes: " + schema.getAttributeCount()); System.out.println("Attributes: "); for (int i = 0; i < schema.getAttributeCount(); i++) { System.out.println(schema.getAttributeDescriptors().get(i).getName()); } // 获取要素信息 SimpleFeatureCollection collection = dataStore.getFeatureSource(typeName).getFeatures(); try (SimpleFeatureIterator features = collection.features()) { while (features.hasNext()) { SimpleFeature feature = features.next(); System.out.println(feature.getID() + ": " + feature.getDefaultGeometryProperty().getValue()); } } dataStore.dispose(); } } ``` 需要注意的是,需要在pom.xml中添加geotools依赖: ```xml <dependency> <groupId>org.geotools</groupId> <artifactId>gt-shapefile</artifactId> <version>24.0</version> </dependency> ```

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值