java - 将新的列属性添加到 shapefile 并使用 Geotools Java 将其保存到数据库

标签 java attributes postgis shapefile geotools

我正在通过添加新的列属性来转换 shapefile。由于此任务是使用 Java 执行的,因此我目前知道的唯一选择是使用 Geotools。我有两个主要担忧:

<强>1。我无法弄清楚如何实际添加新的列变量。 feature.setAttribute("col","value") 是答案吗?

我从这篇文章中看到的只是一个例子:https://gis.stackexchange.com/questions/215660/modifying-feature-attributes-of-a-shapefile-in-geotools但我没有得到解决方案。

   //Upload the ShapeFile
    File file = JFileDataStoreChooser.showOpenFile("shp", null);
    Map<String, Object> params = new HashMap<>();
    params.put("url", file.toURI().toURL());

    DataStore store = DataStoreFinder.getDataStore(params);
    SimpleFeatureSource featureSource = store.getFeatureSource(store.getTypeNames()[0]);
    String typeName = store.getTypeNames()[0];


     FeatureSource<SimpleFeatureType, SimpleFeature> source =
            store.getFeatureSource(typeName);
        Filter filter = Filter.INCLUDE;

    FeatureCollection<SimpleFeatureType, SimpleFeature> collection = source.getFeatures(filter);
    try (FeatureIterator<SimpleFeature> features = collection.features()) {
        while (features.hasNext()) {
            SimpleFeature feature = features.next();

            //adding new columns

            feature.setAttribute("ShapeID", "SHP1213");
            feature.setAttribute("UserName", "John");

            System.out.print(feature.getID());
            System.out.print(":");
            System.out.println(feature.getDefaultGeometryProperty().getValue());
        }
    }

/*
 * Write the features to the shapefile
 */
Transaction transaction = new DefaultTransaction("create");


// featureSource.addFeatureListener(fl);

if (featureSource instanceof SimpleFeatureStore) {
    SimpleFeatureStore featureStore = (SimpleFeatureStore) featureSource;

    featureStore.setTransaction(transaction);
    try {
        featureStore.addFeatures(collection);
        transaction.commit();

    } catch (Exception problem) {
        problem.printStackTrace();
        transaction.rollback();

    } finally {
        transaction.close();
    }
    System.exit(0); // success!
} else {
    System.out.println(typeName + " does not support read/write access");
    System.exit(1);
}

假设 setattribute 是添加的,我在上述代码中收到以下错误。

Exception in thread "main" org.geotools.feature.IllegalAttributeException:Unknown attribute ShapeID:null value:null
    at org.geotools.feature.simple.SimpleFeatureImpl.setAttribute(SimpleFeatureImpl.java:238)
    at org.geotools.Testing.WritetoDatabase.main(WritetoDatabase.java:73)

<强>2。修改这些更改后,我想将其存储在数据库(PostGIS)中。我发现下面的代码片段可以完成任务,但仅插入形状文件似乎对我不起作用

  Properties params = new Properties();
    params.put("user", "postgres");
    params.put("passwd", "postgres");
    params.put("port", "5432");
    params.put("host", "127.0.0.1");
    params.put("database", "test");
    params.put("dbtype", "postgis");

  dataStore = DataStoreFinder.getDataStore(params);

在上述情况下,错误是 NullPointerException。

最佳答案

在 GeoTools 中,(简单)FeatureType 是不可变的(不可更改),因此您不能只向 shapefile 添加新属性。因此,首先您必须创建一个包含新属性的新功能类型。

FileDataStore ds = FileDataStoreFinder.getDataStore(new File("/home/ian/Data/states/states.shp"));
SimpleFeatureType schema = ds.getSchema();
// create new schema
SimpleFeatureTypeBuilder builder = new SimpleFeatureTypeBuilder();
builder.setName(schema.getName());
builder.setSuperType((SimpleFeatureType) schema.getSuper());
builder.addAll(schema.getAttributeDescriptors());
// add new attribute(s)
builder.add("shapeID", String.class);
// build new schema
SimpleFeatureType nSchema = builder.buildFeatureType();

然后,您需要将所有现有功能转换为新架构并添加新属性。

// loop through features adding new attribute
List<SimpleFeature> features = new ArrayList<>();
try (SimpleFeatureIterator itr = ds.getFeatureSource().getFeatures().features()) {
  while (itr.hasNext()) {
    SimpleFeature f = itr.next();
    SimpleFeature f2 = DataUtilities.reType(nSchema, f);
    f2.setAttribute("shapeID", "newAttrValue");
    //System.out.println(f2);
    features.add(f2);
  }
}

最后,打开 Postgis 数据存储并向其中写入新功能。

Properties params = new Properties();
params.put("user", "postgres");
params.put("passwd", "postgres");
params.put("port", "5432");
params.put("host", "127.0.0.1");
params.put("database", "test");
params.put("dbtype", "postgis");

DataStore dataStore = DataStoreFinder.getDataStore(params);
SimpleFeatureSource source = dataStore.getFeatureSource("tablename");
if (source instanceof SimpleFeatureStore) {
  SimpleFeatureStore store = (SimpleFeatureStore) source;
  store.addFeatures(DataUtilities.collection(features));
} else {
  System.err.println("Unable to write to database");
}

关于java - 将新的列属性添加到 shapefile 并使用 Geotools Java 将其保存到数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52554587/

相关文章:

postgresql - Osm2pgsql 由于错误 : Cannot detect file format 而失败

java - Ear 项目动态 Web 应用程序和 Maven

java - 如何通过 eclipse RCP 中的不同执行来更新和维护查看器状态?

ruby - ruby 类中的可继承属性

properties - 没有值(value)的 Vue 组件 Prop

java - 检索 JTextPane AttributeSet 值

java - 在过程内动态添加的表上创建触发器

Java/XSLT 字符编码

ruby-on-rails - zip : How to make only one query with 2 queries

java - Spring boot 应用程序失败方法 org.postgresql.jdbc4.Jdbc4Connection.createClob() 尚未实现