首页 > 其他分享 >Shapefile代码示例

Shapefile代码示例

时间:2025-01-05 18:04:05浏览次数:1  
标签:-- String 示例 Shapefile 代码 shpPath shpCharset new FileUtil

Shapefile代码示例

1. 读取Shapefile文件

1.1 实现思路

graph TD A[查找必要文件] --> B[获取文件编码] B --> C[打开图层] C --> D[获取要素集] D --> G[关闭图层]

1.2 代码示例


    public static SimpleFeatureCollection readShp(String shpPath) {
        List<String> bys = CollUtil.newArrayList(".shp",".shx",".dbf",".prj");
        for (String by : bys) {
            String path = CharSequenceUtil.replaceLast(shpPath, ".shp", by,true);
            if(!FileUtil.exist(path)){
                throw new RuntimeException(by+"类型的文件不存在");
            }
        }

        Charset shpCharset = null;
        String cpgPath = CharSequenceUtil.replaceLast(shpPath, ".shp", ".cpg",true);
        if(FileUtil.exist(cpgPath)){
            File cpgFile = FileUtil.file(cpgPath);
            Charset cpgCharset = CharsetDetector.detect(cpgFile);
            String cpgString = FileUtil.readString(cpgFile, cpgCharset);
            try {
                shpCharset = Charset.forName(cpgString.trim());
            } catch (Exception e) {
                throw new RuntimeException("CPG文件保存的编码格式错误");
            }
        }
        
        if (shpCharset == null) {
            String dbfPath = CharSequenceUtil.replaceLast(shpPath, ".shp", ".dbf",true);
            if(FileUtil.exist(dbfPath)){
                byte[] bs = FileUtil.readBytes(dbfPath);
                if (bs != null && bs.length >= 30) {
                    byte b = bs[29];
                    if (b == 0x4d) {
                        shpCharset = Charset.forName("GBK");
                    }
                }
            }
        }

        if(shpCharset == null){
            shpCharset = StandardCharsets.UTF_8;
        }
        
        try {
            File file = new File(shpPath);
            ShapefileDataStore shpDataStore = new ShapefileDataStore(file.toURI().toURL());
            shpDataStore.setCharset(shpCharset);
            String typeName = shpDataStore.getTypeNames()[0];
            SimpleFeatureSource source = shpDataStore.getFeatureSource(typeName);
            shpDataStore.dispose();
            return source.getFeatures();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

Shapefile文件编码参考文档

2. 写入Shapefile文件

2.1 实现思路

graph TD A[构建图层结构] --> B[写入要素] B --> C[关闭图层] C --> D[写入编码]

2.2 代码示例


    public static void writeShp(String shpPath, SimpleFeatureCollection featureCollection){
        try {
            File shapeFile = new File(shpPath);
            Map<String, Serializable> params = new HashMap<>();
            params.put(ShapefileDataStoreFactory.URLP.key, shapeFile.toURI().toURL());

            ShapefileDataStore ds = (ShapefileDataStore) new ShapefileDataStoreFactory().createNewDataStore(params);
            SimpleFeatureType featureType = featureCollection.getSchema();
            ds.createSchema(featureType);
            Charset charset = StandardCharsets.UTF_8;
            ds.setCharset(charset);

            String typeName = ds.getTypeNames()[0];
            FeatureWriter<SimpleFeatureType, SimpleFeature> writer = ds.getFeatureWriterAppend(typeName, Transaction.AUTO_COMMIT);

            try (FeatureIterator<SimpleFeature> features = featureCollection.features()) {
                while (features.hasNext()) {
                    SimpleFeature feature = features.next();
                    writer.hasNext();
                    SimpleFeature writefeature = writer.next();
                    writefeature.setDefaultGeometry(feature.getDefaultGeometry());

                    for (PropertyDescriptor d : featureType.getDescriptors()) {
                        if (!(feature.getAttribute(d.getName()) instanceof Geometry)) {
                            Name name = d.getName();
                            Object value = feature.getAttribute(name);
                            writefeature.setAttribute(name, value);
                        }
                    }

                    writer.write();
                }
            }

            writer.close();
            ds.dispose();

            String cpgPath = shpPath.substring(0, shpPath.lastIndexOf(".")) + ".cpg";
            FileUtil.writeString("UTF-8", cpgPath, StandardCharsets.UTF_8);
        }catch (Exception e){
            throw new RuntimeException(e);
        }
    }

3. Shapefile代码操作的原则

  • 默认使用UTF-8编码格式,根据实际情况处理编码问题

标签:--,String,示例,Shapefile,代码,shpPath,shpCharset,new,FileUtil
From: https://www.cnblogs.com/znlgis/p/18653571

相关文章

  • PostGIS代码操作简介
    PostGIS代码操作简介1.代码操作POSTGIS的可选方案jdbcpostgis-javageotoolsgdal2.JDBCpublicvoidtestJdbc(){Stringsql="selectst_area(st_geomfromtext('MULTIPOLYGON(((39364656.25041901320219042701523.9713633288629353,39364650.8289328......
  • GeoJSON代码示例
    GeoJSON代码示例1.读取GeoJSON文件1.1实现思路graphTDA[读取GeoJSON文件]-->B[读取GeoJSON文件内容]B-->C[解析GeoJSON文件内容]C-->D[构建SimpleFeatureCollection]D-->E[返回SimpleFeatureCollection]1.2代码示例publicstaticSim......
  • FileGDB代码示例
    FileGDB代码示例返回1.读取FileGDB图层1.1实现思路graphTDA[注册OGR]-->B[设置中文路径支持]B-->C[打开数据驱动]C-->D[打开数据源]D-->G[获取图层]G-->H[读取图层信息]1.2代码示例publicLayerreadGdbLayer(StringdriverName,......
  • uniapp - 详解使用高德地图在地图上实现绘制边界/点聚合/行政区域高亮等功能,Uniapp高
    效果图在uni-app手机h5网页网站/支付宝微信小程序/安卓app/苹果app/nvue等(全平台兼容)开发中,实现各端都兼容的“安装使用高德地图并实现点聚合/地图绘制边界部分高亮显示”,高德地图点聚合标记及高德地图绘制行政边界等,标点窗体信息展示,在高德地图上标点及卡片气泡框面板......
  • 【Java 代码审计入门-06】文件包含漏洞原理与实际案例介绍
    【Java代码审计入门-06】文件包含漏洞原理与实际案例介绍0x00写在前面为什么会有这一些列的文章呢?因为我发现网上没有成系列的文章或者教程,基本上是Java代码审计中某个点来阐述的,对于新人来说可能不是那么友好,加上本人也在学习Java审计,想做个学习历程的记录和总结,因此......
  • 分析师关注度、分析师跟踪、研报关注度(2001-2023年)原始数据、参考文献、代码do文件、
    分析师关注度、分析师跟踪、研报关注度(2001-2023年)原始数据、参考文献、代码do文件、最终结果 https://download.csdn.net/download/2401_84585615/90025540           https://download.csdn.net/download/2401_84585615/90025540      ......
  • 数据挖掘算法之【8k 字详解FpGrowth算法】—— 附加python代码案例
    大家好,我是摇光~,用大白话讲解所有你难懂的知识点之前用大白话讲了Apriori算法,如果不懂Apriori算法,可以去看这篇文章:7k字详解Apriori算法我们在说Apriori算法的时候,讲过他的缺点,因为要对数据库做频繁的遍历,会产品大量的候选项集,增加计算的复杂性。比如长度为1的频......
  • 安全框架SpringSecurity进阶【详解,附有图文+示例代码】
    文章目录十二.SpringSecurity进阶12.1认证流程12.2简单实现(无权限)思路分析准备工作导入依赖添加Redis相关配置Redis使用FastJson序列化RedisCache缓存Redis配置类响应类JWT工具类WebUtils工具类数据库准备实体类yml配置文件实现配置密码加密器12.3自定义登录接口12.......
  • 基于多目标蜣螂优化算法NSDBO求解微电网多目标优化调度的Matlab代码
    一、非支配排序的蜣螂优化算法NSDBO求解微电网多目标优化调度问题简介 非支配排序的蜣螂优化算法(Non-dominatedSortingDragonflyAlgorithm,NSDBO)是一种用于求解多目标优化问题的算法。它主要用于解决微电网多目标优化调度问题。NSDBO算法基于蜣螂优化算法(DragonflyAlgor......
  • paddleocr 识别的核心部分的代码
    Lib\site-packages\paddleocr\tools\infer\predict_system.py(用的python39目录里边的库def__call__(self,img,cls=True,slice={}):time_dict={"det":0,"rec":0,"cls":0,"all":0}ifimgisNone:logg......