在geotools中是不直接支持对shp文件结构的直接更改的,在需要删除字段/增加字段的要求下,我就需要重新建立schema:
/**
* 创建新的字段结构
* @param oldSchema 传入老的结构
* @return
* @throws Exception
*/
private static SimpleFeatureType modifyScheme(SimpleFeatureType oldSchema) throws Exception {
try {
// 创建新的结构
SimpleFeatureTypeBuilder builder = new SimpleFeatureTypeBuilder();
builder.setName(oldSchema.getName());
builder.setSuperType((SimpleFeatureType) oldSchema.getSuper());
builder.addAll(oldSchema.getAttributeDescriptors());
//删除原有的某个字段
//builder.remove("oldField");
// 添加新的字段
//相交面积
builder.add("newField1", Double.class);
//行政区划面积
builder.add("newField2", Double.class);
// 构建信息的结构
SimpleFeatureType newSchema = builder.buildFeatureType();
return newSchema;
}catch(Exception exception) {
throw new Exception(exception.getMessage());
}
}
然后再用新的scheme进行赋值,原来的值并不会被替代,默认带入到新的schema中:
//修改属性表
SimpleFeatureType newSchema = modifyScheme(cityCollection.getSchema());
SimpleFeatureIterator iterator = subFeatureCollection.features();
List<SimpleFeature> newFeatures = new ArrayList<>();
while (iterator.hasNext()) {
SimpleFeature cityFeature = iterator.next();
Geometry cityGeo = (Geometry)cityFeature.getDefaultGeometry();
Geometry intersectGeo = cityGeo.intersection(unionZone);
SimpleFeature newFeature = DataUtilities.reType(newSchema, cityFeature);
//新字段赋值
newFeature.setAttribute("newField1", 1);
//新字段赋值
newFeature.setAttribute("newField2", 2);
newFeatures.add(newFeature);
}
iterator.close();
SimpleFeatureCollection newSimpleFeatureCollection = DataUtilities.collection(newFeatures);