第五章 Java代码解析shape数据到数据库中

解析单个shape测试(Java代码解析shape到数据库中)

第七章 Java解析单个shape-CSDN博客

1 代码解析geotoos解析shape

1.1依赖

<repositories>
  <repository>
    <id>central</id>
    <name>aliyun maven</name>
    <url>https://maven.aliyun.com/repository/central</url>
    <snapshots>
      <enabled>false</enabled>
    </snapshots>
    <releases>
      <enabled>true</enabled>
    </releases>
  </repository>

  <repository>
    <id>osgeo-releases</id>
    <name>OSGeo Nexus 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-snapshots</id>
    <name>OSGeo Nexus Snapshot Repository</name>
    <url>https://repo.osgeo.org/repository/snapshot/</url>
    <snapshots>
      <enabled>false</enabled>
    </snapshots>
    <releases>
      <enabled>true</enabled>
    </releases>
  </repository>

  <repository>
    <id>geosolutions</id>
    <name>geosolutions repository</name>
    <url>https://maven.geo-solutions.it/</url>
    <snapshots>
      <enabled>false</enabled>
    </snapshots>
    <releases>
      <enabled>true</enabled>
    </releases>
  </repository>
</repositories>

<dependencies>
<dependency>
  <groupId>org.apache.commons</groupId>
  <artifactId>commons-compress</artifactId>
  <version>1.7</version>
</dependency>
<dependency>
  <groupId>org.geotools</groupId>
  <artifactId>gt-shapefile</artifactId>
  <version>23.0</version>
</dependency>
<dependency>
  <groupId>org.geotools</groupId>
  <artifactId>gt-geojson</artifactId>
  <version>23.0</version>
</dependency>
<dependency>
  <groupId>org.geotools</groupId>
  <artifactId>gt-epsg-hsql</artifactId>
  <version>23.0</version>
</dependency>
<dependency>
    <groupId>junit</groupId>
    <artifactId>junit</artifactId>
    <version>RELEASE</version>
</dependency>

</dependencies>

1.2 代码

1.2.1 解析shap

public class ShapeXin {
    public static Object read(String path) throws IOException {
       /*
         参数path就是shp文件的完整路径,如:E:\\蟠桃会资源清查\\调查图斑.shp
         系统会自动检查同一个目录下有没有其他相关文件,有的话会一并读出,
         相关文件的路径无须给出
         .shp 存储地理形状和位置信息
         .dbf 存储属性信息
         .shx 索引文件
         .prj 坐标系
         .cpg 字符编码,如UTF-8

         读取出来的结果类型为 List<Map<String, Object>>
       */
        List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();

        File file = getFile(path);
        if (file == null) {
            return list;
        }

        String charset = getCharSet(path);

        FileDataStore store = FileDataStoreFinder.getDataStore(file);
        ((ShapefileDataStore)store).setCharset(Charset.forName(charset));
        SimpleFeatureSource featureSource = store.getFeatureSource();
        SimpleFeatureCollection collection = featureSource.getFeatures();
        SimpleFeatureIterator features = collection.features();

        while (features.hasNext()) {
            Map<String, Object> item = new HashMap<String, Object>();

            SimpleFeature f = features.next();
            Collection<Property> p = f.getProperties();
            Iterator<Property> it = p.iterator();
//            System.out.println("-----------------");
            System.out.println(f.getType());
//            System.out.println("-----------------");
            ;
            while (it.hasNext()) {
                Property pro = it.next();

                String field = pro.getName().toString();
                field = field.equals("the_geom") ? "wkt" : field;

                String value = pro.getValue().toString();
                item.put(field, value);
            }

            list.add(item);
        }

        return list;
    }

    private static File getFile(String path){
        File file = new File(path);
        if (file == null) {
            System.out.println("找不到路径:" + path);
        }
        return file;
    }
    /*
       获取shapefile字符编码
       如果存在.cpg文件,则从中读取,否则默认为UTF-8
     */
    private static String getCharSet(String path){
        String charset = "GBK";

        int p = path.lastIndexOf(".");
        String cpg = path.substring(0,p) + ".cpg";
        if(cpg==null || cpg==""){
            cpg = path.substring(0,p) + ".CPG";
        }
        File file = getFile(cpg);
        if(file != null) {
            RandomAccessFile raf = null;
            try {
                raf = new RandomAccessFile(cpg, "r");
                charset = raf.readLine();
                raf.close();
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return charset;
    }
}

1.2.2 service

public interface ShapeService {
    /**
     * 空间点附件保存
     *
     * @param
     * @return
     */
    public int  save(List<Map<String,Object>> jie);
}

1.2.3 serviceimpl

import com.yinghui.soft.mapper.TBaseGeometryTableMapper;
import com.yinghui.soft.mapper.TBaseGeompointMapper;
import com.yinghui.soft.model.TBaseGeometryTable;
import com.yinghui.soft.model.TBaseGeompoint;
import com.yinghui.soft.service.ShapeService;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

@Service
public class ShapeServiceImpl implements ShapeService{
    private Logger logger = LoggerFactory.getLogger(ShapeServiceImpl.class);
    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Autowired
    private  TBaseGeometryTableMapper mapper;


    @Override
    public int save(List<Map<String, Object>> jie) {
        TBaseGeometryTable tBaseGeometryTable;
        for (Map<String, Object> listMap : jie) {
          tBaseGeometryTable=new TBaseGeometryTable();
            String wktStr = (String) listMap.get("wkt");
            String name = (String) listMap.get("QH_NAME");
            if(name==null || name==""){
                name=(String) listMap.get("XZQMC");
            }
            if(name==null || name==""){
                name=(String) listMap.get("NAME");
            }
            if(name==null || name==""){
                name=(String) listMap.get("地块名");
            }
            String geom="SRID=4326;"+wktStr;
            tBaseGeometryTable.setGeom(geom);
            tBaseGeometryTable.setName(name);
            mapper.insertSelective(tBaseGeometryTable);
        }
        return 1;
    }
}

1.2.4 Controller

import com.yinghui.soft.geotools.JieYa;
import com.yinghui.soft.geotools.ShapeXin;

import com.yinghui.soft.service.ShapeService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;



@RequestMapping("/shape")
@RestController
public class TBaseJieYaController extends BaseController  {

    private Logger logger = LoggerFactory.getLogger(TBaseJieYaController.class);

    @Value("${tomcatPath}")
    String tomcatPath;
    @Value("${tomcatUrl}")
    String tomcatUrl;
    @Value("${fileTag}")
    String fileTag;
    @Value("${nextFile}")
    String nextFile;

    @Autowired
    private ShapeService shapeService;

    @ResponseBody
    @RequestMapping(value = "/ya", method = RequestMethod.POST)
    public Map delete(HttpServletRequest request, @RequestParam("url") MultipartFile file) {
        Map map = new HashMap(4);
        try{

            //定义文件上传地址
            String url="";
            String infoUrl="";
            String fileName = file.getOriginalFilename();
            String subStr =  fileName.substring(fileName.lastIndexOf("."),fileName.length());
            String data= new SimpleDateFormat("yyyyMMdd").format(new Date());
            String newFileName=  new Date().getTime()+"";
            String urlWj="";
            String xin;
            try{
                url=tomcatPath+ File.separator+fileTag+ File.separator+nextFile+ File.separator+data+"\\";
                File f = new File(url);
                if(!f.exists()){
                    f.mkdirs();
                }
               urlWj=tomcatPath+ File.separator+fileTag+ File.separator+nextFile+ File.separator+data+File.separator+newFileName+subStr;
                xin=tomcatPath+ File.separator+fileTag+ File.separator+nextFile+ File.separator+data+File.separator;

                //  输入流
                InputStream is = file.getInputStream();
                //创建一个文件输出流
                FileOutputStream fos = new FileOutputStream(urlWj);
                //创建一个缓冲区
                byte buffer[] = new byte[1024];
                //判断输入流中的数据是否已经读完的标识
                int length = 0;
                //循环将输入流读入到缓冲区当中,(len=in.read(buffer))>0就表示in里面还有数据
                while((length = is.read(buffer))>0){
                    //使用FileOutputStream输出流将缓冲区的数据写入到指定的目录(savePath + "\\" + filename)当中
                    fos.write(buffer, 0, length);
                }
                //关闭输入流
                is.close();
                //关闭输出流
                fos.close();
                infoUrl="/"+fileTag+"/"+nextFile+"/"+data+"/"+newFileName+subStr;


            }catch (Exception e){
                e.printStackTrace();
                map.put("flag",false);
                map.put("msg","文件上传出错");
                return map;
            }

            /**
             * 1.上传文件进行,放到固定的文件夹中,获取到固定文件夹的地址
             */
            String path=tomcatPath;
            String suffixName=fileName.substring(fileName.lastIndexOf("."));//获取文件后缀

            try {

                logger.info(urlWj+"-----===");
                /**
                 *2.进行解压文件夹,传送一个shape文件地址
                 */
                 String jie= JieYa.unZip(new File(urlWj),xin);
                /**
                 * 3.拿到shape文件地址,进行解析shape文件
                 */
               logger.info(""+jie);
                 if(jie.length()<=0){
                     map.put("flag", false);
                     map.put("msg", "解析失败");
                 }
                 List<Map<String, Object>> list = (List<Map<String, Object>>) ShapeXin.read(jie);

               logger.info(String.valueOf(list));
                /**
                 *
                 * 4.拿到shape中的数据进行往数据库中添加
                 * **/

                int ce=shapeService.save(list);
                if(ce==1){
                    map.put("flag", true);
                    map.put("msg", "导入成功");
                }

            } catch (Exception e) {
                e.printStackTrace();
                map.put("flag", false);
                map.put("msg", "执行失败");
            }

        } catch (Exception e) {
            logger.error("参数错误", e);
            map.put("flag", false);
            map.put("msg", "参数错误");
        }

        return map;
    }
}

2 postman测试接口

2.1写请求地址,请求方式

2.2 在Body下中的KEY写上参数

2.3VALUE下点击Select Files按钮

选择要上传的zip文件

注意:只能是zip文件

 

2.4 点击send

出现以下界面就证明导入成功

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

akglobe

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值