public static void readShpFile(String shpPath) {File shpFile = new File(shpPath);try {// 通过给定的shapefile路径创建ShapefileDataStore对象ShapefileDataStore shapefileDataStore = new ShapefileDataStore(shpFile.toURI().toURL());// 设置编码为UTF-8,以防止属性中的中文字符出现乱码shapefileDataStore.setCharset(Charset.forName("UTF-8"));// 获取FeatureSource对象,用于获取要素集合并进行操作FeatureSource featuresource = shapefileDataStore.getFeatureSource(shapefileDataStore.getTypeNames()[0]);// 读取边界框(bbox)ReferencedEnvelope bbox = featuresource.getBounds();// 读取投影(坐标参考系统)CoordinateReferenceSystem crs = featuresource.getSchema().getCoordinateReferenceSystem();// 获取总要素数量int count = featuresource.getCount(Query.ALL);// 获取要素集合的几何类型(点、线、面等)GeometryType geometryType = featuresource.getSchema().getGeometryDescriptor().getType();// 读取要素集合SimpleFeatureCollection simpleFeatureCollection = (SimpleFeatureCollection) featuresource.getFeatures();// 获取属性字段列表List<AttributeDescriptor> attributes = simpleFeatureCollection.getSchema().getAttributeDescriptors();// 获取要素迭代器SimpleFeatureIterator simpleFeatureIterator = simpleFeatureCollection.features();// 遍历每一个要素while(simpleFeatureIterator.hasNext()) {SimpleFeature simpleFeature = simpleFeatureIterator.next();// 使用Java 8的流API遍历每一个属性值,并处理其他业务逻辑attributes.stream().forEach((a) -> {// 依次读取shapefile中每一个属性的值System.out.println(a.getLocalName() + ":" + simpleFeature.getAttribute(a.getLocalName()));});}} catch (IOException e) {e.printStackTrace();}System.out.println("读取完成!");
}
以上代码是一个用于读取 Shapefile 文件的方法。该方法的主要功能包括:
- 创建 ShapefileDataStore 对象,用于读取 Shapefile 文件的数据源。
- 设置编码为 UTF-8 避免属性中的中文字符乱码。
- 获取 FeatureSource 对象,用于获取要素集合和元数据。
- 读取边界框(bbox)和投影(坐标参考系统)信息。
- 获取要素集合的总数量和几何类型。
- 读取要素集合,并获取属性字段列表。
- 遍历每一个要素,并打印每个属性字段的值。
最后,输出读取完成的提示信息。
这段代码提供了一个简单的方式来读取 Shapefile 文件,并获取其中要素和属性的信息。你可以根据需要进一步处理和使用这些数据。