栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

Java 读取shp文件,生成shp文件,通过shp文件自动建库

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Java 读取shp文件,生成shp文件,通过shp文件自动建库


    private static final String GEOMETRY_TYPE_POINT = "Point";
    private static final String GEOMETRY_TYPE_MULTIPOINT = "MultiPoint";
    private static final String GEOMETRY_TYPE_LINESTRING = "LineString";
    private static final String GEOMETRY_TYPE_MULTILINESTRING = "MultiLineString";
    private static final String GEOMETRY_TYPE_POLYGON = "Polygon";
    private static final String GEOMETRY_TYPE_MULTIPOLYGON = "MultiPolygon";

    
    public static void write2Shape(String shpPath, String encode, String authority,String geoType, List geoms) {
        try {
            //创建shape文件对象
            File file = new File(shpPath);
            Map params = new HashMap<>();
            ShapefileDataStore ds = new ShapefileDataStore(file.toURI().toURL());

            //定义图形信息和属性信息
            SimpleFeatureTypeBuilder tb = new SimpleFeatureTypeBuilder();
            //坐标框架
            CoordinateReferenceSystem sourceCRS = CRS.decode(authority);
            tb.setCRS(sourceCRS);

            tb.setName("shapefile");

            if (GEOMETRY_TYPE_POINT.equals(geoType)) {
                tb.add("the_geom", Point.class);
            } else if (GEOMETRY_TYPE_MULTIPOINT.equals(geoType)) {
                tb.add("the_geom", MultiPoint.class);
            } else if (GEOMETRY_TYPE_LINESTRING.equals(geoType)) {
                tb.add("the_geom", LineString.class);
            } else if (GEOMETRY_TYPE_MULTILINESTRING.equals(geoType)) {
                tb.add("the_geom", MultiLineString.class);
            }else if (GEOMETRY_TYPE_POLYGON.equals(geoType)) {
                tb.add("the_geom", Polygon.class);
            } else if (GEOMETRY_TYPE_MULTIPOLYGON.equals(geoType)) {
                tb.add("the_geom", MultiPolygon.class);
            } else {
                throw new Exception("Geometry中没有该类型:" + geoType);
            }

            ds.createSchema(tb.buildFeatureType());
            //设置编码
            Charset charset = Charset.forName(encode);
            ds.setCharset(charset);
            //设置Writer
            FeatureWriter writer = ds.getFeatureWriter(ds.getTypeNames()[0], Transaction.AUTO_COMMIT);
            for (Geometry geom : geoms) {
                //String type = geom.getGeometryType();

                SimpleFeature feature = writer.next();

                feature.setAttribute("the_geom", geom);
            }
            writer.write();
            writer.close();
            ds.dispose();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    
    public static void write2Shape(String shpPath, String encode, String prjWKT, String geoType, String shpKey, List attrKeys, List> data) throws Exception{

        if (data == null || data.size() == 0) {
            return;
        }
        //创建shape文件对象
        File file = new File(shpPath);
        ShapefileDataStore ds = new ShapefileDataStore(file.toURI().toURL());

        //定义图形信息和属性信息
        SimpleFeatureTypeBuilder tb = new SimpleFeatureTypeBuilder();
        //坐标框架
        //CoordinateReferenceSystem sourceCRS = CRS.decode(authority);
        CoordinateReferenceSystem sourceCRS = CRS.parseWKT(prjWKT);
        tb.setCRS(sourceCRS);
        tb.setName("shapefile");

        CoordinateReferenceSystem middleCRS = CRS.decode("EPSG:4490");
        MathTransform transform = CRS.findMathTransform(middleCRS, sourceCRS);
        //MathTransform transform = CRS.findMathTransform(DefaultGeographicCRS.WGS84, sourceCRS);

        if (GEOMETRY_TYPE_POINT.equals(geoType)) {
            tb.add("the_geom", Point.class);
        } else if (GEOMETRY_TYPE_MULTIPOINT.equals(geoType)) {
            tb.add("the_geom", MultiPoint.class);
        } else if (GEOMETRY_TYPE_LINESTRING.equals(geoType)) {
            tb.add("the_geom", LineString.class);
        } else if (GEOMETRY_TYPE_MULTILINESTRING.equals(geoType)) {
            tb.add("the_geom", MultiLineString.class);
        }else if (GEOMETRY_TYPE_POLYGON.equals(geoType)) {
            tb.add("the_geom", Polygon.class);
        } else if (GEOMETRY_TYPE_MULTIPOLYGON.equals(geoType)) {
            tb.add("the_geom", MultiPolygon.class);
        } else {
            throw new Exception("Geometry中没有该类型:" + geoType);
        }

        for (String field : attrKeys) {
            tb.add(field.toUpperCase(), String.class);
        }

        ds.createSchema(tb.buildFeatureType());
        //设置编码
        Charset charset = Charset.forName(encode);
        ds.setCharset(charset);
        //设置Writer
        FeatureWriter writer = ds.getFeatureWriter(ds.getTypeNames()[0], Transaction.AUTO_COMMIT);
        //写入文件信息
        for (int i = 0; i < data.size(); i++) {
            SimpleFeature feature = writer.next();
            Map row = data.get(i);
            Geometry geom = (Geometry) row.get(shpKey);

            for(int j=0;j getAttrOfShp(String shpFile) throws Exception {

        List> result = new ArrayList>();
        SimpleFeatureSource featureSource = null;

        File file = new File(shpFile);
        ShapefileDataStore shpDataStore = null;

        shpDataStore = new ShapefileDataStore(file.toURI().toURL());
        //设置编码
        //Charset charset = Charset.forName("UTF-8");
        Charset charset = Charset.forName("GBK");
        shpDataStore.setCharset(charset);
        String tableName = shpDataStore.getTypeNames()[0];
        featureSource = shpDataStore.getFeatureSource(tableName);
        SimpleFeatureType schema = featureSource.getSchema();
        ArrayList fields = new ArrayList<>();

        schema.getAttributeDescriptors().forEach(attr-> {
            Class cls = attr.getType().getBinding();
             String length = GetLength(attr.getType().getRestrictions());
            //获取属性名称
            String clsName = cls.getName();
            if(!attr.getLocalName().equals("the_geom")) {
                clsName = clsName.substring(clsName.lastIndexOf(".") + 1).toLowerCase();
                if (length == null || "".equals(length)) {
                    Fields field = new Fields(attr.getLocalName(), clsName, 0);
                    field = typeJudgment(field);
                    fields.add(field);
                } else {
                    Fields field = new Fields(attr.getLocalName(), clsName, Integer.parseInt(length));
                    field = typeJudgment(field);
                    fields.add(field);
                }
            }
        });
        System.out.println(fields);
        return fields;
    }



    
    public static List> readSHP(String shpFile, int spatialRef, List arrKeys) throws Exception{

        List> result = new ArrayList>();
        SimpleFeatureSource featureSource = null;

        File file = new File(shpFile);
        ShapefileDataStore shpDataStore = null;

        shpDataStore = new ShapefileDataStore(file.toURI().toURL());
        //设置编码
        //Charset charset = Charset.forName("UTF-8");
        Charset charset = Charset.forName("GBK");
        shpDataStore.setCharset(charset);
        String tableName = shpDataStore.getTypeNames()[0];
        featureSource = shpDataStore.getFeatureSource(tableName);

        SimpleFeatureCollection featureCollection = featureSource.getFeatures();
        SimpleFeatureType featureType = featureCollection.getSchema();
        CoordinateReferenceSystem coordinateReferenceSystem = featureType.getCoordinateReferenceSystem();


        SimpleFeatureIterator features = featureCollection.features();
        while(features.hasNext()){
            SimpleFeature feature = features.next();
            ArrayList fieldValues = new ArrayList<>();
            arrKeys.parallelStream().forEach(ar->{
                Object fieldValue = feature.getAttribute(ar);
                if(fieldValue == null) {
                    fieldValues.add("null");
                }else{
                    fieldValues.add("'"+fieldValue+"'");
                }
            });
            Geometry geom = (Geometry) feature.getAttribute("the_geom");
            CoordinateReferenceSystem crsTarget = CRS.decode("EPSG:" + spatialRef,true);
            int wkid = 0;
            wkid = CRS.lookupEpsgCode(crsTarget,true);
            // 投影转换
            String srs = CRS.lookupIdentifier(featureType.getCoordinateReferenceSystem(), true);
            MathTransform transform = CRS.findMathTransform(CRS.decode(srs,true), crsTarget);
            Geometry transformGeom = JTS.transform(geom, transform);

            if(transformGeom instanceof Point){
                fieldValues.add("ST_GeomFromText('"+((Point)transformGeom).toString()+"',"+wkid+")");
            }else if(transformGeom instanceof LineString){
                fieldValues.add("ST_GeomFromText('"+((LineString)transformGeom).toString()+"',"+wkid+")");
            }else if(transformGeom instanceof Polygon){
                fieldValues.add("ST_GeomFromText('"+((Polygon)transformGeom).toString()+"',"+wkid+")");
            }else if(transformGeom instanceof MultiPoint){
                fieldValues.add("ST_GeomFromText('"+((MultiPoint)transformGeom).toString()+"',"+wkid+")");
            }else if(transformGeom instanceof MultiLineString){
                fieldValues.add("ST_GeomFromText('"+((MultiLineString)transformGeom).toString()+"',"+wkid+")");
            }else if(transformGeom instanceof  MultiPolygon){
                fieldValues.add("ST_GeomFromText('"+((MultiPolygon)transformGeom).toString()+"',"+wkid+")");
            }
            result.add(fieldValues);
        }
        return result;
    }


    
    private  static  String GetLength(Object o){
        String string = o.toString();
        List lis = Arrays.asList(string.split(""));
        String current="";
        for (int i = 0; i < lis.size(); i++) {
            String s = lis.get(i);
            boolean integer = isInteger(s);
            if (integer){
                current+=s;
            }
        }
        return current;
    }

    
    public static boolean isInteger(String str) {
        String rgex="[0-9]*";
        Pattern pattern = Pattern.compile(rgex);
        return pattern.matcher(str).matches();
    }


    

   public static Fields typeJudgment(Fields field){
        if(field.getDataType().equals("integer")||field.getDataType().equals("long")){
            if(field.getLength() <= 4) {
                field.setDataType("int2");
            }
            else{
                field.setDataType("int4");
            }
            field.setLength(0);
        }
        else if(field.getDataType().equals("double")){
            if(field.getLength() <= 13){
                field.setDataType("float8");
            }else{
                field.setDataType("numeric");
            }
            field.setLength(0);
        }else if(field.getDataType().equals("string")){
            field.setDataType("varchar");
        }else if(field.getDataType().equals("date")){
            field.setLength(0);
        }
        return  field;
        }


转载请注明:文章转载自 www.mshxw.com
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号