gdal-java

GDAL-java读取shp文件信息

2019-06-08  本文已影响0人  WebGiser

ReadShp.java代码

package Vector;

import org.gdal.gdal.gdal;
import org.gdal.ogr.*;
import org.gdal.osr.SpatialReference;
import java.util.HashMap;
import java.util.Map;

//读取某个磁盘路径下的shp文件信息(范围、属性等)
public class ReadShp {
    public static void main(String[] args) throws Exception {
        //指定文件的名字和路径
        String strVectorFile ="E:\\test\\test.shp";

        // 注册所有的驱动
        ogr.RegisterAll();

        //配置GDAL_DATA路径(gdal根目录下的bin\gdal-data)
        gdal.SetConfigOption("GDAL_DATA","F:\\GDAL学习文件夹\\release-1900-x64-gdal-2-3-2-mapserver-7-2-1\\bin\\gdal-data");

        // 为了支持中文路径,请添加下面这句代码
        gdal.SetConfigOption("GDAL_FILENAME_IS_UTF8","YES");

        // 为了使属性表字段支持中文,请添加下面这句
        gdal.SetConfigOption("SHAPE_ENCODING","CP936");

        //读取数据,这里以ESRI的shp文件为例
        String strDriverName = "ESRI Shapefile";

        //创建一个文件,根据strDriverName扩展名自动判断驱动类型
        org.gdal.ogr.Driver oDriver =ogr.GetDriverByName(strDriverName);
        if (oDriver == null) {
            System.out.println(strDriverName+ " 驱动不可用!\n");
            return;
        }
        DataSource dataSource = oDriver.Open(strVectorFile);
        Layer layer = dataSource.GetLayer("test");

        String layerName = layer.GetName();
        System.out.println("图层名称:"+layerName);

        SpatialReference spatialReference = layer.GetSpatialRef();
        //System.out.println(spatialReference);
        System.out.println("空间参考坐标系:"+spatialReference.GetAttrValue("AUTHORITY",0)+spatialReference.GetAttrValue("AUTHORITY",1));



        double[] layerExtent = layer.GetExtent();
        System.out.println("图层范围:minx:"+layerExtent[0]+",maxx:"+layerExtent[1]+",miny:"+layerExtent[2]+",maxy:"+layerExtent[3]);

        FeatureDefn featureDefn = layer.GetLayerDefn();
        int fieldCount = featureDefn.GetFieldCount();
        Map<String,Object> fieldMap = new HashMap();
        for(int i=0; i<fieldCount; i++){
            FieldDefn fieldDefn = featureDefn.GetFieldDefn(i);
            //得到属性字段类型
            int fieldType = fieldDefn.GetFieldType();
            String fieldTypeName = fieldDefn.GetFieldTypeName(fieldType);
            //得到属性字段名称
            String fieldName = fieldDefn.GetName();

            fieldMap.put(fieldTypeName,fieldName);
        }

        long featureCount = layer.GetFeatureCount();
        System.out.println("图层要素个数:"+featureCount);
        for(int i=0; i<featureCount; i++){
            Feature feature = layer.GetFeature(i);
            Object[] arr = fieldMap.values().toArray();
            for(int k=0; k<arr.length; k++){
                String fvalue = feature.GetFieldAsString(arr[k].toString());
                System.out.print(" 属性名称:"+arr[k].toString()+",属性值:"+fvalue);
            }
            System.out.println();
        }
    }
}
image.png
上一篇下一篇

猜你喜欢

热点阅读