最近参与了一个GIS项目,记录一下吧:

postgresql数据库:

  • geometry数据类型转wkt格式:st_astext(geometry)
  • wkt格式数据转geometry数据类型: st_geomfromtext(wkt数据,坐标系参数),若无法使用,则st_geometry(wkt数据,坐标系参数)

用户上传zip文件,解析zip里的shp相关文件,获取wkt数据并返回:

分别需要解析两个文件,shp文件(获取wkt数据)  prj文件(获取坐标系,是一个整数)

Maven相关
<properties><java.version>1.8</java.version><geotools.version>18.4</geotools.version></properties><dependency><groupId>org.geotools</groupId><artifactId>gt-shapefile</artifactId><version>${geotools.version}</version></dependency><dependency><groupId>org.geotools</groupId><artifactId>gt-geojson</artifactId><version>${geotools.version}</version></dependency><dependency><groupId>org.geotools</groupId><artifactId>gt-main</artifactId><version>${geotools.version}</version></dependency><dependency><groupId>org.geotools</groupId><artifactId>gt-epsg-extension</artifactId><version>${geotools.version}</version></dependency><dependency><groupId>org.geotools</groupId><artifactId>gt-referencing</artifactId><version>${geotools.version}</version></dependency><repositories><repository><id>osgeo</id><name>OSGeo Release Repository</name><url>https://repo.osgeo.org/repository/release/</url><snapshots><enabled>false</enabled></snapshots><releases><enabled>true</enabled></releases></repository><repository><id>osgeo-snapshot</id><name>OSGeo Snapshot Repository</name><url>https://repo.osgeo.org/repository/snapshot/</url><snapshots><enabled>true</enabled></snapshots><releases><enabled>false</enabled></releases></repository></repositories>
public class ShapeFileUtils {/*** shp相关文件涉及的 后缀名* */private static final String hasSuffix = "shp dbf shx prj";/*** 临时存放shp相关文件的根目录(Global为本地自定义的配置文件映射类)* */private static final String tempShpDir = Global.getTempFilePath();/*** 解压zip文件,获取shp相关文件,并解析.shp .prj文件,获取数据返回给前端* @param file 要保存到本地的文件* @return 解析完的数据* */public static List<Map<String,Object>>  saveMultipartFile(MultipartFile file){//创建根目录String savePath = tempShpDir+UUID.randomUUID() ;try {//先将zip文件存放到本地,解析完后删除File localFile = new File(savePath+File.separator+getMultipartFileName(file.getOriginalFilename()));localFile.mkdirs();file.transferTo(localFile);//解析文件List<Map<String, Object>> list = resolveZip(localFile, savePath);return list;} catch (IOException e) {e.printStackTrace();return  null ;}finally {//保存完相关文件后,删除压缩包和相关文件 File parentDir = new File(savePath);File[] files = parentDir.listFiles();for (File f: files) {if(f.delete()){//文件一直被占用无法删除,直接调用gc()回收垃圾,简单粗暴System.gc();f.delete();}}if(files.length>0){for (File f: files) {if(f.delete()){f.delete();}}}parentDir.delete();}}/*** 从zip文件中获取 .shp .dbf .shx .prj 四个文件,并预存到本地* @param srcFile        zip源文件* @param savePath       临时文件保存路径* @throws RuntimeException 解压失败会抛出运行时异常* */public static List<Map<String,Object>> resolveZip(File srcFile,String savePath) {//解压文件ZipFile zipFile = null;//.shp文件的存放路径String shpFilePath = "";//.prj文件的存放路径String prjFilePath = "" ;try {zipFile = new ZipFile(srcFile, Charset.forName("GBK"));Enumeration<? extends ZipEntry> entries = zipFile.entries();
//特别注意,entries包含了zip文件里的所有文件,包括子文件夹里的文件,而不仅仅只是压缩包里的第一层文件while(entries.hasMoreElements()){ZipEntry zipEntry = entries.nextElement();//判断是文件夹 或者 文件if(zipEntry.isDirectory()){continue;}else{//判断是否为我们需要的文件if(hasSuffix.indexOf(zipEntry.getName().split("\\.")[1])!=-1){//先临时保存到本地String fileName = zipEntry.getName();if(fileName.lastIndexOf("/") != -1){fileName = fileName.substring(fileName.lastIndexOf("/")+1);}File shpFile = new File(savePath + File.separator+fileName);//获取.shp文件的保存路径if(shpFilePath.indexOf("shp")==-1){shpFilePath = shpFile.getName().indexOf("shp")!=-1 ? shpFile.getAbsolutePath():"" ;}//获取.prj文件的保存路径if(prjFilePath.indexOf("prj")==-1){prjFilePath = shpFile.getName().indexOf("prj")!=-1 ? shpFile.getAbsolutePath():"" ;}shpFile.createNewFile();copyFile(zipFile.getInputStream(zipEntry),new FileOutputStream(shpFile));}}}//解析prj文件,获取坐标系Integer sRid = getSrid(prjFilePath);//解析shp文件,wkt数据List<Map<String, Object>> list = readShapeFile(shpFilePath,sRid);return  list;} catch (IOException e) {throw new RuntimeException("上传shp文件错误:"+e.getMessage());}finally {if(zipFile!=null){try {zipFile.close();} catch (IOException e) {e.printStackTrace();}}}}/*** 解析shp文件* @param path 文件所在路径* @param sRid 坐标系* */public static List<Map<String,Object>> readShapeFile(String path,Integer sRid){File file = new File(path);if(file==null){return null ;}//map记录shapefile key-value数据List<Map<String, Object>> list = new ArrayList<>();try {//通过store获取featurecollectionFileDataStore store = FileDataStoreFinder.getDataStore(file);SimpleFeatureSource featureSource = store.getFeatureSource();SimpleFeatureCollection features = featureSource.getFeatures();SimpleFeatureIterator iterator = features.features();//遍历featurecollectionwhile (iterator.hasNext()){Map<String,Object> data = new HashMap<>();SimpleFeature feature = iterator.next();Collection<Property> properties = feature.getProperties();Iterator<Property> it = properties.iterator();//遍历feature的propertieswhile(it.hasNext()){Property pro = it.next();String field = pro.getName().toString();String value = pro.getValue().toString();//转码 防止中文乱码byte[]bytes=value.getBytes("iso8859-1");value=new String(bytes, "UTF-8");data.put(field,value);}//放入坐标系data.put("srid",sRid);list.add(data);}//解析完毕后关闭store,否则文件无法删除store.dispose();return list;} catch (IOException e) {throw new RuntimeException("解析shp文件失败:"+e.getMessage());}}/***解析prj文件,获取坐标系** @param shpFilePath prj文件路径* @return 坐标系的code ,例如3857,4326等等*/public static Integer getSrid(String shpFilePath) {ShapefileDataStore dataStore = buildDataStore(shpFilePath);Integer code = null;try {String wkt = dataStore.getSchema().getCoordinateReferenceSystem().toWKT();CoordinateReferenceSystem crsTarget = CRS.parseWKT(wkt);code = CRS.lookupEpsgCode(crsTarget,true);} catch (UnsupportedOperationException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();} catch (FactoryException e) {e.printStackTrace();} finally {dataStore.dispose();}return code;}/*** 构建ShapeDataStore对象。* @param shpFilePath shape文件路径。* @return*/public static ShapefileDataStore buildDataStore(String shpFilePath) {ShapefileDataStoreFactory factory = new ShapefileDataStoreFactory();try {ShapefileDataStore dataStore = (ShapefileDataStore) factory.createDataStore(new File(shpFilePath).toURI().toURL());if (dataStore != null) {dataStore.setCharset(Charset.forName("UTF-8"));}return dataStore;} catch (MalformedURLException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();}return null;}/*** 复制文件* @param  in 原文件流输入流* @param out 目标文件输出流* */public static void copyFile(InputStream in, OutputStream out) {int len ;byte[] b = new byte[1024];try {while ((len = in.read(b,0,1024))!=-1){out.write(b,0,len);out.flush();}in.close();out.close();} catch (IOException e) {e.printStackTrace();}finally {try {in.close();out.close();} catch (IOException e) {e.printStackTrace();}}}/*** MultipartFile获取文件名* */public static String getMultipartFileName(String fileName){//判断浏览器,ie浏览器会获取文件的路径,我们不需要路径// Linuxint unixSep = fileName.lastIndexOf('/');// Windowsint winSep = fileName.lastIndexOf('\\');int pos = (winSep > unixSep ? winSep : unixSep);if (pos != -1)  {fileName = fileName.substring(pos + 1);}return  fileName;}
}

Geotools解析shp文件相关推荐

  1. GeoJson的生成与解析,JSON解析,Java读写geojson,geotools读取shp文件,Geotools中Geometry对象与GeoJson的相互转换

    GeoJson的生成与解析 一.wkt格式的geometry转成json格式 二.json格式转wkt格式 三.json格式的数据进行解析 四.Java读写geojson 五.geotools读取sh ...

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

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

  3. java使用geotools读取shp文件

    java使用geotools读取shp文件 测试shp文件 引入geotools包 压缩包文件处理 shp文件相关信息的读取 运行结果 GeoTools是一个开源的Java GIS工具包,可利用它来开 ...

  4. geotools读取shp文件及shp文件操作工具类代码

    geotools读取shp文件及shp文件操作工具类代码.pdf 完整文档下载地址 https://download.csdn.net/download/a772304419/17468931 imp ...

  5. GeoTools读取shp文件中文乱码解决方案汇总

    Java在GeoTools组件读取Shp文件属性乱码问题,解决汇总(持续更新,暂时没有完美解决方案) GeoTools组件在读取Shp文件的属性表信息时,当读取到中文字符时,在代码中的显示为乱码. 问 ...

  6. html中加载shp文件,运用shapefile.js解析Shp文件

    shapefile.open("http://localhost:8181/shp/zd.shp") .then(source => source.read() .then( ...

  7. SpringBoot + geotools 操作 shp文件

    SpringBoot整合GeoTools 1.GeoTools相关的依赖 2.本文所用到的公共类及实体类 3.本文所用到的数据库表 4.WKT格式怎么转化为GeoJson格式 5.GeoJson格式怎 ...

  8. html 显示shp,运用shapefile.js解析Shp文件

    shapefile.open("http://localhost:8181/shp/zd.shp") .then(source => source.read() .then( ...

  9. php解析shapefile,运用shapefile.js解析Shp文件

    shapefile.open("http://localhost:8181/shp/zd.shp") .then(source => source.read() .then( ...

  10. World Wind Java开发之六——解析shape文件(转)

    http://blog.csdn.net/giser_whu/article/details/41647117 最近一直忙于导师项目的事情了,几天没更新了,昨天和今天研究了下WWJ解析shp文件的源代 ...

最新文章

  1. php接收一维数组中文乱码解决
  2. 关于c++ template的branching和Recursion的一段很好的描述
  3. 史上最全Vim快捷键键位图(入门到进阶)
  4. 分库分表下极致的优化
  5. 淮安中专学计算机哪个学校好,2021淮安初中十强排名 哪些初中比较好
  6. 【渝粤教育】广东开放大学 商法 形成性考核 (40)
  7. Java高级语法笔记-接口(interface)
  8. java map 实例_java中map集合嵌套形式简单示例
  9. 神经网络一(Neural Network)
  10. java飞机大战boss素材_java小游戏飞机大战 源代码以及素材
  11. 如何提升设备管理效率和巡检效率?
  12. windows版微信Hook开发SDK之C#版-微信二次开发
  13. 解决iPhone无法连接iTunes
  14. 使用GPU进行神经网络计算详解
  15. Win10系统设置IP无法保存解决方式
  16. 快解析结合友加畅捷通t1飞跃版
  17. gzip bzip2 区别
  18. 我的面试经历3-OPPO
  19. 欧尼酱讲JVM(10)——操作数栈
  20. nrf5 SDK中 FDS(Flash Data Storage)介绍

热门文章

  1. 计算机程序设计在线课程,最新章节测试答案2020学堂在线计算机程序设计基础(先修课)...
  2. 离散数学杜忠复版答案_离散数学(第二版)课后习题答案详解(完整版)
  3. 嵌入式应用程序下载到ARM开发板后如何运行程序?
  4. rpc portmap rpcbind vxi11
  5. Google各项产品汇总(附链接)
  6. 高速公路坐标高程计算软件3.1版发布
  7. python测网速_tespeed-测试网速的Python工具
  8. Linux内核memcpy的不同实现
  9. 趋势科技防毒墙-网络版(OfficeScan)客户端管理工具
  10. 【Apple苹果设备刷机】ipad已停用,iTunes无法联系网络等问题