问题描述
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();