通过geotools读写shp文件
时间: 2023-07-08 17:34:46 浏览: 142
java基于geotools实现shapefile几何数据批量读取通用工具类,实现shp数据通用批量读取,shapefile读取
5星 · 资源好评率100%
可以使用Geotools库来读写shp文件。下面是一个简单的示例代码,可以读取shp文件并打印出其属性表信息:
```java
import java.io.File;
import java.io.IOException;
import org.geotools.data.DataStore;
import org.geotools.data.DataStoreFinder;
import org.geotools.data.simple.SimpleFeatureCollection;
import org.geotools.data.simple.SimpleFeatureIterator;
import org.opengis.feature.simple.SimpleFeature;
import org.opengis.feature.simple.SimpleFeatureType;
public class ShpFileReader {
public static void main(String[] args) throws IOException {
// 读取shp文件
File file = new File("path/to/shapefile.shp");
DataStore dataStore = DataStoreFinder.getDataStore(file);
String typeName = dataStore.getTypeNames()[0];
SimpleFeatureType schema = dataStore.getSchema(typeName);
// 获取属性表信息
System.out.println("Feature Type: " + typeName);
System.out.println("Number of attributes: " + schema.getAttributeCount());
System.out.println("Attributes: ");
for (int i = 0; i < schema.getAttributeCount(); i++) {
System.out.println(schema.getAttributeDescriptors().get(i).getName());
}
// 获取要素信息
SimpleFeatureCollection collection = dataStore.getFeatureSource(typeName).getFeatures();
try (SimpleFeatureIterator features = collection.features()) {
while (features.hasNext()) {
SimpleFeature feature = features.next();
System.out.println(feature.getID() + ": " + feature.getDefaultGeometryProperty().getValue());
}
}
dataStore.dispose();
}
}
```
需要注意的是,需要在pom.xml中添加geotools依赖:
```xml
<dependency>
<groupId>org.geotools</groupId>
<artifactId>gt-shapefile</artifactId>
<version>24.0</version>
</dependency>
```
阅读全文