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')
请问我遗漏了什么内容?
解决方法
- 修正类型转换错误
getFeatureWriterAppend方法返回的是FeatureWriter<SimpleFeatureType, SimpleFeature>类型,不能直接强转为SimpleFeatureWriter,需使用正确的类型声明:
FeatureWriter<SimpleFeatureType, SimpleFeature> writer = dataStore.getFeatureWriterAppend(dataStore.getTypeNames()[0], new DefaultTransaction());
- 修复语法错误
代码中CoordinateReferenceSystem crs = DefaultGeographicCRS.WGS84一行末尾缺少分号,补充后:
CoordinateReferenceSystem crs = DefaultGeographicCRS.WGS84;
内容的提问来源于stack exchange,提问作者Mandroid
相关产品推荐
相关产品推荐

