java如何读取shp文件
时间: 2023-07-18 18:38:21 浏览: 109
Java可以使用GeoTools开源库来读取shp文件。下面是一个示例代码:
```java
File file = new File("path/to/shapefile.shp");
Map<String, Object> params = new HashMap<>();
params.put("url", file.toURI().toURL());
DataStore dataStore = DataStoreFinder.getDataStore(params);
String typeName = dataStore.getTypeNames()[0];
FeatureSource<SimpleFeatureType, SimpleFeature> source = dataStore.getFeatureSource(typeName);
FeatureCollection<SimpleFeatureType, SimpleFeature> collection = source.getFeatures();
try (FeatureIterator<SimpleFeature> features = collection.features()) {
while (features.hasNext()) {
SimpleFeature feature = features.next();
// do something with the feature
}
}
```
其中,`path/to/shapefile.shp`需要替换为实际的shp文件路径。在代码中,先通过`DataStoreFinder`获取一个`DataStore`对象,然后通过`getTypeNames()`获取shapefile中的类型名称,进而通过`getFeatureSource()`获取`FeatureSource`对象,最后通过`getFeatures()`获取`FeatureCollection`对象,遍历其中的`Feature`对象即可。
阅读全文