代码改变世界

shp文件的解析方法

2017-07-26 10:15  Lose丶word  阅读(2221)  评论(0编辑  收藏  举报

// 需要先引入gdal.jar架包,同时把文件夹下的dll文件放在项目的根目录。(亲测32位的有效)

// 文件地址 :  http://pan.baidu.com/s/1mhAoqvQ

public String readSHP(String path,String addvcd) {
  // 注册所有的驱动
  ogr.RegisterAll();
  // 为了支持中文路径,请添加下面这句代码
  gdal.SetConfigOption("GDAL_FILENAME_IS_UTF8","YES");
  // 为了使属性表字段支持中文,请添加下面这句 (默认的好像是gbk格式的。utf-8用下面的那行代码)
  gdal.SetConfigOption("SHAPE_ENCODING","");

  //gdal.SetConfigOption("SHAPE_ENCODING","CP936");

  String strVectorFile = path;
  //打开数据
  //在读取shp文件时需要将对应的shx文件放在同一目录下,否则会出错
  DataSource ds = ogr.Open(strVectorFile,0);
  //DataSource ds = ogr.Open(strVectorFile);
  if(ds == null) {
    System.out.println("未找到文件!");
    return null;
  }

  Driver dv = ogr.GetDriverByName("GeoJSON");
  if (dv == null)
  {
    System.out.println("打开驱动失败!" );
    return null;
  }

  // 获取编译后的路径
  String url = "D:\\node.json";

  // 判断文件中是否已存在该json文件,有则删除. 
  File file = new File(url);
  if (file.exists()) {
    file.delete();
  } else {
    System.out.println("文件不存在");
  }

  // 把shp格式转为json格式后,生成json文件
  dv.CopyDataSource(ds, url);

 

  // 根据需求,我这里是直接返回生成的路径就行。如果是要返回json文件的内容,则需要打开下面这些代码,修改返回值 sresult 
  // 解析json,拼接json内容  

  /*String sresult = "";
  try {
    BufferedReader br = new BufferedReader(new FileReader("D:\\node.json")); // 读取原始json文件
  try {
  String valueString = null;
  while ((valueString=br.readLine()) != null){ // 循环拼接json文本内容
    sresult = sresult + valueString;
  }
  } catch (IOException e) {
    e.printStackTrace();
  }
  } catch (FileNotFoundException e) {
    e.printStackTrace();
  }*/

  return url;
}