首页 > 学院 > 开发设计 > 正文

ShapeFile工具类

2019-11-11 04:58:54
字体:
来源:转载
供稿:网友

使用GeoTools读取ShapeFile文件,测试版本为geotools-16.1。 所需jar包有 这里写图片描述

package com.test;import java.io.File;import java.nio.charset.Charset;import java.util.ArrayList;import java.util.List;import org.geotools.data.shapefile.ShapefileDataStore;import org.geotools.data.shapefile.ShapefileDataStoreFactory;import org.geotools.data.shapefile.files.ShpFiles;import org.geotools.data.shapefile.shp.ShapefileReader;import org.geotools.data.simple.SimpleFeatureCollection;import org.geotools.data.simple.SimpleFeatureSource;import com.vividsolutions.jts.geom.Geometry;import com.vividsolutions.jts.geom.GeometryFactory;public class ShapeFileUtils { /** * 获取shape文件feature集合 * @param shapePath shape文件路径 * @param charSet 读取shape文件编码 * @return SimpleFeatureCollection */ public static SimpleFeatureCollection ReadShapeFileFeatures(String shapePath, String charSet){ SimpleFeatureCollection sfc = null; ShapefileDataStoreFactory dataStoreFactory = new ShapefileDataStoreFactory(); ShapefileDataStore sds = null; try { sds = (ShapefileDataStore)dataStoreFactory.createDataStore(new File(shapePath).toURI().toURL()); sds.setCharset(Charset.forName(charSet)); SimpleFeatureSource featureSource = sds.getFeatureSource(); sfc = featureSource.getFeatures(); } catch (Exception e) { e.PRintStackTrace(); }finally{ sds.dispose(); } return sfc; } /** * 读取ShapeFile中的空间数据 * @param shapeFilePath * @return List<Geometry> */ public static List<Geometry> getGeometriesFromShapeFile(String shapeFilePath){ List<Geometry> result = new ArrayList<Geometry>(); try { ShpFiles file = new ShpFiles(shapeFilePath); ShapefileReader reader = new ShapefileReader(file, false, false, new GeometryFactory()); while(reader.hasNext()){ result.add((Geometry)reader.nextRecord().shape()); } reader.close(); } catch (Exception e) { e.printStackTrace(); } return result; }}

测试类如下。

package com.test;import org.geotools.data.simple.SimpleFeatureCollection;import org.geotools.data.simple.SimpleFeatureIterator;import org.opengis.feature.simple.SimpleFeature;import com.tongtu.mobile.cuanalysis.utils.ShapeFileUtils;import com.vividsolutions.jts.geom.Geometry;public class ShapeFileTest { public static void main(String[] args) throws Exception{ SimpleFeatureCollection sfc = ShapeFileUtils.ReadShapeFileFeatures("D://ziptest//bou.shp", "GBK"); SimpleFeatureIterator iterator = sfc.features(); while(iterator.hasNext()) { SimpleFeature feature = iterator.next(); System.out.println(feature.getAttribute("NAME"));//获取属性名称 Geometry g = (Geometry) feature.getDefaultGeometry();//获取空间数据 System.out.println(g.toString()); } iterator.close(); }}

工具类持续完善中…… 参考资料:http://www.cnblogs.com/cugwx/p/3719195.html


发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表