You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Geotools创建Shapefile的SimpleFeatureWriter时遇类型转换异常

GeoTools编写Shapefile时出现ClassCastException问题

问题描述

我尝试编写Shapefile,代码如下:

File shapefile = new File(....);
Map<String, Serializable> map = new HashMap();
map.put("url", shapefile.toURI().toURL());
SimpleFeatureTypeBuilder builder = new SimpleFeatureTypeBuilder();
builder.setName("MultiPolygonFeatureType");
CoordinateReferenceSystem crs = DefaultGeographicCRS.WGS84
builder.setCRS(crs);
builder.add("location", MultiPolygon.class);
builder.add("name", String.class);
SimpleFeatureType featureType = builder.buildFeatureType();
ShapefileDataStoreFactory factory = new ShapefileDataStoreFactory();
ShapefileDataStore dataStore = (ShapefileDataStore) factory.createNewDataStore(map);
dataStore.createSchema(featureType);
SimpleFeatureWriter writer = (SimpleFeatureWriter) dataStore.getFeatureWriterAppend(dataStore.getTypeNames()[0], new DefaultTransaction());

运行时报错:

java.lang.ClassCastException: class org.geotools.data.InProcessLockingManager$1 cannot be cast to class org.geotools.data.simple.SimpleFeatureWriter(org.geotools.data.InProcessLockingManager$1 and org.geotools.data.simple.SimpleFeatureWriter are in unnamed module of loader 'app')

请问我遗漏了什么内容?

解决方法

  1. 修正类型转换错误
    getFeatureWriterAppend方法返回的是FeatureWriter<SimpleFeatureType, SimpleFeature>类型,不能直接强转为SimpleFeatureWriter,需使用正确的类型声明:
FeatureWriter<SimpleFeatureType, SimpleFeature> writer = dataStore.getFeatureWriterAppend(dataStore.getTypeNames()[0], new DefaultTransaction());
  1. 修复语法错误
    代码中CoordinateReferenceSystem crs = DefaultGeographicCRS.WGS84一行末尾缺少分号,补充后:
CoordinateReferenceSystem crs = DefaultGeographicCRS.WGS84;

内容的提问来源于stack exchange,提问作者Mandroid

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.16 13:09:54