【Java使用Geotools对shp文件进行读取,读取完成之后shp、dbf、shx文件总是被占用,无法删除,如何解决呢?】

Java使用Geotools对shp文件进行读取,读取完成之后shp、dbf、shx文件总是被占用,无法删除,如何解决呢?

问题描述

Java使用Geotools对shp文件进行读取,读取完成之后.shp、.dbf、.shx文件总是被占用,无法删除。
在这里插入图片描述
读取shp的代码块:

try {
            ShapefileDataStore shapefileDataStore = new ShapefileDataStore(shpfile.toURI().toURL());
            //设置编码,防止中文乱码
            Charset charset = getShapeFileCharsetName(shapePath);
//            Charset charset = Charset.forName("GBK");
            shapefileDataStore.setCharset(charset);
            String typeName = shapefileDataStore.getTypeNames()[0];
            //根据图层名称来获取要素的source
            SimpleFeatureSource featureSource = shapefileDataStore.getFeatureSource(typeName);
            //读取bbox
            ReferencedEnvelope bbox = featureSource.getBounds();
            //读取投影
            CoordinateReferenceSystem crs = featureSource.getSchema().getCoordinateReferenceSystem();
            //坐标系转换
            //判断坐标系是否为EPSG:4326
            if (!crs.getCoordinateSystem().getName().toString().contains("GCS_WGS_1984")) {
                return error("图层坐标系不是WGS84坐标系,请先进行坐标系转换!");
            }
            //特征总数
            int count = featureSource.getCount(Query.ALL);
            //获取当前数据的geometry类型(点、线、面)
            GeometryType geometryType = featureSource.getSchema().getGeometryDescriptor().getType();
            //读取要素
            SimpleFeatureCollection simpleFeatureCollection = (SimpleFeatureCollection) featureSource.getFeatures();
            // 字段
            List<AttributeDescriptor> attributes = simpleFeatureCollection.getSchema().getAttributeDescriptors();
            SimpleFeatureIterator simpleFeatureIterator = simpleFeatureCollection.features();
            while (simpleFeatureIterator.hasNext()) {
            //其他解析代码
            ......
            }

原因分析与问题解决

在使用 GeoTools 读取 Shapefile 后文件被占用的问题,通常是因为未正确释放资源。以下是解决方案:

1.直接原因

代码中创建的 ShapefileDataStore 和 SimpleFeatureIterator 未显式关闭,导致底层文件句柄未释放。

(1)代码中使用了ShapefileDataStore 来读取shp文件。根据GeoTools的文档,ShapefileDataStore 在打开后需要正确关闭,否则可能会保持文件句柄打开,导致文件被占用。
(2)同时SimpleFeatureIterator读取数据的迭代器也需要正确关闭。
两者缺一不可。

2.解决方案

显式调用 shapefileDataStore.dispose(); 和 simpleFeatureIterator.close();方法。(兼容所有版本)
调用的顺序:

//1.先调用迭代器关闭
simpleFeatureIterator.close();

//2.再调用store关闭
shapefileDataStore.dispose(); 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

haokan_Jia

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

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

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

打赏作者

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

抵扣说明:

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

余额充值