直接上代码


import org.geotools.data.*;
import org.geotools.data.collection.ListFeatureCollection;
import org.geotools.data.shapefile.ShapefileDataStore;
import org.geotools.data.shapefile.ShapefileDataStoreFactory;
import org.geotools.data.simple.SimpleFeatureCollection;
import org.geotools.data.simple.SimpleFeatureSource;
import org.geotools.data.simple.SimpleFeatureStore;
import org.geotools.feature.FeatureCollection;
import org.geotools.feature.FeatureIterator;
import org.geotools.feature.simple.SimpleFeatureBuilder;
import org.geotools.geojson.GeoJSONUtil;
import org.geotools.geojson.feature.FeatureJSON;
import org.geotools.geojson.geom.GeometryJSON;
import org.geotools.referencing.CRS;
import org.locationtech.jts.geom.*;
import org.opengis.feature.simple.SimpleFeature;
import org.opengis.feature.simple.SimpleFeatureType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.*;public class RwUtils {private static Logger logger = LoggerFactory.getLogger(RwUtils.class);public static List<? extends Geometry> toSimple(List<? extends Geometry> geometryList) {List< Geometry> simpleLineList = new ArrayList<>();for (Geometry geometry : geometryList) {if (geometry instanceof MultiLineString || geometry instanceof MultiPolygon || geometry instanceof MultiPoint) {for (int j = 0; j < geometry.getNumGeometries(); j += 1) {simpleLineList.add(geometry.getGeometryN(j));}} else if (geometry instanceof LineString || geometry instanceof Polygon || geometry instanceof Point) {simpleLineList.add(geometry);}}return simpleLineList;}public static List<SimpleFeature> toSimpleFeature(List<SimpleFeature> simpleFeatureList){List<SimpleFeature> resultList = new ArrayList<>();for (SimpleFeature simpleFeature: simpleFeatureList) {Geometry geometry = (Geometry) simpleFeature.getDefaultGeometry();if (geometry instanceof MultiLineString || geometry instanceof MultiPolygon || geometry instanceof MultiPoint) {for (int i = 0; i < geometry.getNumGeometries(); i += 1) {SimpleFeature clone = SimpleFeatureBuilder.deep(simpleFeature);clone.setDefaultGeometry(geometry.getGeometryN(i));resultList.add(clone);}} else if (geometry instanceof LineString || geometry instanceof Polygon || geometry instanceof Point) {resultList.add(simpleFeature);}}return resultList;}public static List<LineString> toSimpleLine(List<? extends Geometry> geometryList) {List<LineString> simpleLineList = new ArrayList<>();for (Geometry geometry : geometryList) {if (geometry instanceof MultiLineString) {for (int j = 0; j < geometry.getNumGeometries(); j += 1) {simpleLineList.add((LineString) geometry.getGeometryN(j));}} else if (geometry instanceof LineString) {simpleLineList.add((LineString) geometry);}}return simpleLineList;}public static List<Geometry>  readFeaturesShp(String path){List<Geometry> geometryList = new ArrayList<>();try {File file = new File(path);Map<String, Object> map = new HashMap<>();map.put("url", file.toURI().toURL());DataStore dataStore = DataStoreFinder.getDataStore(map);String typeName = dataStore.getTypeNames()[0];FeatureSource<SimpleFeatureType, SimpleFeature> source =dataStore.getFeatureSource(typeName);
//            Filter filter = Filter.INCLUDE; // ECQL.toFilter("BBOX(THE_GEOM, 10,20,30,40)")geometryList = new ArrayList<>();FeatureCollection<SimpleFeatureType, SimpleFeature> collection = source.getFeatures();
//            features = collection.features();
//            dataStore.dispose();try (FeatureIterator<SimpleFeature> features = collection.features()) {while (features.hasNext()) {SimpleFeature feature = features.next();Geometry geomrtry = (Geometry)feature.getDefaultGeometry();geometryList.add(geomrtry);}features.close();dataStore.dispose();}}catch (Exception e){System.out.println(e);}return geometryList;}public static List<LineString>  readCenterLineFeaturesShp(String path){List<Geometry> geometryList = readFeaturesShp(path);return toSimpleLine(geometryList);}public static List<Geometry> readGeoJson(String geojsonPath){List<Geometry> geometryList = new ArrayList<>();InputStreamReader reader = null;try{reader = new InputStreamReader(new FileInputStream(geojsonPath), "UTF-8");FeatureIterator<SimpleFeature> features = new FeatureJSON().streamFeatureCollection(GeoJSONUtil.toReader(reader));geometryList = new ArrayList<>();while (features.hasNext()) {SimpleFeature feature = features.next();Geometry line = (Geometry) feature.getDefaultGeometry();geometryList.add(line);}}catch (Exception e){logger.error("=======================读取异常:" + e);}finally {try {assert reader != null;reader.close();}catch (Exception e){logger.error("=======================读取流关闭异常:" + e);}}return geometryList;}public static List<LineString> readCenterLine(String path){List<LineString> centerLineList = new ArrayList<>();InputStreamReader reader = null;try{reader = new InputStreamReader(new FileInputStream(path), "UTF-8");FeatureIterator<SimpleFeature> features = new FeatureJSON().streamFeatureCollection(GeoJSONUtil.toReader(reader));List<Geometry> centerGeomList = new ArrayList<>();while (features.hasNext()) {SimpleFeature feature = features.next();Geometry line = (Geometry) feature.getDefaultGeometry();centerGeomList.add(line);}centerLineList = toSimpleLine(centerGeomList);}catch (Exception e){logger.error("=======================读取异常:" + e);}finally {try {assert reader != null;reader.close();}catch (Exception e){logger.error("=======================读取流关闭异常:" + e);}}return centerLineList;}public static List<SimpleFeature> readCenterLineFeatures(String path){List<SimpleFeature> featureList = new ArrayList<>();InputStreamReader reader = null;try{reader = new InputStreamReader(new FileInputStream(path), "UTF-8");FeatureIterator<SimpleFeature> features = new FeatureJSON().streamFeatureCollection(GeoJSONUtil.toReader(reader));while (features.hasNext()) {SimpleFeature feature = features.next();featureList.add(feature);}}catch (Exception e){logger.error("=======================读取异常:" + e);}finally {try {assert reader != null;reader.close();}catch (Exception e){logger.error("=======================读取流关闭异常:" + e);}}return featureList;}public static void featureToShp(String path, List<SimpleFeature> outFeatures){try {FileDataStoreFactorySpi factory = new ShapefileDataStoreFactory();File file = new File(path);if (file.exists()) {return;}Map map = Collections.singletonMap("url", file.toURI().toURL());ShapefileDataStore dataStore = (ShapefileDataStore)factory.createNewDataStore(map);SimpleFeatureType featureType =outFeatures.get(0).getType();dataStore.createSchema(featureType);dataStore.forceSchemaCRS(CRS.decode("EPSG:3857"));/** Write the features to the shapefile*/Transaction transaction = new DefaultTransaction("create");String typeName = dataStore.getTypeNames()[0];SimpleFeatureSource featureSource = dataStore.getFeatureSource(typeName);if (featureSource instanceof SimpleFeatureStore) {SimpleFeatureStore featureStore = (SimpleFeatureStore) featureSource;SimpleFeatureCollection collection = new ListFeatureCollection(featureType, outFeatures);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);}}catch (Exception e){System.out.println(e);}}public static void featureToGeojson(String path, List<SimpleFeature> outFeatures){Writer gjsonWriter = null;try{File file = new File(path);if (file.exists()) {file.delete();}if (outFeatures.isEmpty()) {return;}FeatureJSON featureJSON = new FeatureJSON(new GeometryJSON(6));
//            CoordinateReferenceSystem sourceCRS = CRS.decode("EPSG:3857");gjsonWriter = new OutputStreamWriter(new FileOutputStream(singleRoadPath), StandardCharsets.UTF_8);
//            featureJSON.writeCRS(sourceCRS,gjsonWriter);featureJSON.writeFeatureCollection(new ListFeatureCollection(outFeatures.get(0).getType(), outFeatures), gjsonWriter);}catch (Exception e){logger.error("=======================feature写入异常:" + e);}finally {try{if (gjsonWriter != null) {gjsonWriter.flush();gjsonWriter.close();}}catch (IOException ie){logger.error("=======================流关闭异常:" + ie);}}}public static List<SimpleFeature> geometrysToGeojson( List<? extends Geometry> lineStringList, String lineType){List<SimpleFeature> lineFeatures = new ArrayList<>();try {SimpleFeatureType type = DataUtilities.createType("line", lineType);SimpleFeatureBuilder linefeatureBuilder = new SimpleFeatureBuilder(type);linefeatureBuilder.add("id");for (int i = 0; i < lineStringList.size(); i++) {Geometry centerLine = lineStringList.get(i);if(centerLine == null){continue;}//linefeatureBuilder.set("id", String.valueOf(i));SimpleFeature featureLine = linefeatureBuilder.buildFeature(String.valueOf(i));featureLine.setDefaultGeometry(centerLine);featureLine.setAttribute("id",String.valueOf(i));lineFeatures.add(featureLine);}}catch (Exception e){logger.error("异常:" + e);}return lineFeatures;}public static void geometrysToGeojson(String output, List<? extends Geometry> lineStringList, String lineType){List<SimpleFeature> lineFeatures = geometrysToGeojson(lineStringList, lineType);featureToGeojson(output, lineFeatures);}public static void geometrysToShp(String output, List<? extends Geometry> lineStringList, String lineType){List<SimpleFeature> lineFeatures = geometrysToGeojson(lineStringList, lineType);featureToShp(output, lineFeatures);}public static List<LineString> filterLinesByLen(List<LineString> simpleLineList, float filterLen){List<LineString> filterLineList = new ArrayList<>();for (LineString simpleLine: simpleLineList) {if(simpleLine.getLength() >= filterLen){filterLineList.add(simpleLine);}}return filterLineList;}}

读写shp等空间数据,进行geometry、SimpleFeature等转换的工具类相关推荐

  1. java解析shp文件以及坐标转换(工具类)

    百度找了很多大部分都是pom的,maven项目中的,但是用maven下载不了,只能一个jar一个jar下载了,中间也遇到了很多坑,都是pom中没有提到的架包 直接上代码,最后我会解析shp文件所用到的 ...

  2. 基于POI的读写Excel文件的工具类

    依赖的jar包: import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStrea ...

  3. apache httpclient 工具类_HttpClient 和Mycat 主从节点和读写分离

    第175次(HttpClient) 学习主题:HttpClient 学习目标: 1 掌握HttpClient自定义工具以及HttpClient具体的使用 对应视频: http://www.itbaiz ...

  4. java读写excel文件poi_Java利用POI读写Excel文件工具类

    本文实例为大家分享了Java读写Excel文件工具类的具体代码,供大家参考,具体内容如下 package com.test.app.utils; import java.io.File; import ...

  5. 读写Excel工具类ExcelUtil

    突然要用到Excel的读写操作,自己写太过麻烦,在网上找了好久找到个还不错的工具类,怕自己忘掉,分享出来,也留个记录,以后可以直接拿来用. 这个工具类分三个部分: ExcelUtil.java  // ...

  6. 读写csv,xlsx文件的工具类

    微信搜索:"二十同学" 公众号,欢迎关注一条不一样的成长之路 Java对csv文件和xlsx文件进行读写的工具类,简单易用,代码如下: 需要引用的依赖 <dependency ...

  7. java读写Excel工具类

    本项目采用maven工程,使用poi技术去读取excel表格. 所需jar包为: <!-- https://mvnrepository.com/artifact/org.apache.poi/p ...

  8. 四、EasyExcel实现Excel读写,封装工具类

    在项目中,我们经常用到EasyExcel框架实现:对Excel文件的读写操作.为了方便后续其他项目中的使用,将对Excel文件的读写操作,封装成工具类. 一.EasyExcel实现Excel读写,封装 ...

  9. 一次代码重构之旅-快速读写xml文件工具类封装

    为了满足系统的灵活性,有些功能经常需要用到配置文件,一般是xml格式的居多.如何能快速读写配置文件呢? 以前都是用dom4j提供的api来读写xml文件,用dom4j读写配置文件总感觉像是在结构化的处 ...

最新文章

  1. 换个角度聊系统稳定性建设(2021版)
  2. Ubuntu14.04下安装wechat(微信)
  3. 华为手机的“美国梦”
  4. 交换机网络嗅探方法之用ARP欺骗辅助嗅探
  5. scala Ordering
  6. 华为Mate40国行版18点08分开卖:要求12小时内必须卖完
  7. 无代码动态数据可视化大屏
  8. Javascript验证身份证号码:正则表达式
  9. 无法使用此电子邮件地址。请选择其他电子邮件地址
  10. 可落地的DDD(6)-工程结构
  11. ISO14443 Type B类型卡的防碰撞过程以及命令解析
  12. BIM用C语言编程,实现BIM技术的三个重要方面是()。A.BIM的建立B.BIM的应用C.BIM的管理D.BIM的粒度E.BIM的概念...
  13. threejs官方demo:clipping.html源码学习
  14. 利用matlab与eeglab对EEG信号(脑电)进行处理分段与保存
  15. App渠道打包的最佳攻略,一次解决打包难题
  16. 用类PASCAL语言//实现链表(线性表)
  17. 专访张龙:我的漫漫程序人生路
  18. 绿坝对IT行业的沉重打击,从此只能运行Windows操作系统了
  19. 【imessage代发】群推送苹果协议版本,群发控制代码相关结合
  20. WiFi(6)和5G的区别及比对

热门文章

  1. F1-score值计算
  2. java定时开始和关闭_springboot自带定时器实现定时任务的开启关闭以及定时时间可以配置详解...
  3. ddpush php,GitHub - brok1n/ddpushWebManager: DDPUSH 的web管理解决方案
  4. ENVI无法打开landsat level2级产品的解决办法
  5. 为什么机油使用后变红_汽车机油用完后放出油红色怎么回事
  6. 制度是绝情的,管理是无情的,执行是合情的
  7. 模仿Airbnb的悬浮搜索框动画
  8. CFA一级通过率如何?
  9. git中提示 please tell me who you are
  10. lwm2m和coap协议 简解读