Wechat: yu389741| Email: gisdqy@163.com

Shop:https://www.giserdqy.com/shop

【Java OGR开发】如何创建空的矢量shapfile文件



目的:使用GDAL创建空的矢量图层文件,图层类型可知,空间参考不可知,无要素;
起初,使用以下代码创建图层,但当加入到ArcMap中时,报错: could not open the specified file

ogr.RegisterAll();
// 为了支持中文路径,请添加下面这句代码
gdal.SetConfigOption("GDAL_FILENAME_IS_UTF8", "YES");
String newFilePath = "图层的完整路径";
String strDriverName = "ESRI Shapefile";
org.gdal.ogr.Driver oDriver = ogr.GetDriverByName(strDriverName);
if (oDriver == null) {
    throw new CreateLayerException(newFilePath + " 生成失败\n");
}
DataSource oDS = oDriver.CreateDataSource(newFilePath, null);
if (oDS == null) {
    throw new CreateLayerException("文件【" + newFilePath + "】打开失败\n");
}

Layer oLayer = oDS.CreateLayer("parking", null,abstractLayer.getLayerType(), null);
if (oLayer == null) {
    throw new CreateLayerException("创建图层失败");
}
FieldDefn oFieldID = new FieldDefn("id", ogr.OFTString);
oLayer.CreateField(oFieldID, 1);

oLayer.SyncToDisk();
oDS.SyncToDisk();

后发现,当建立好图层之后,随意创建一个要素添加到图层,便可打开,于是采用了一个不是特别好的方法来解决这个问题:创建图层后添加一个要素,而后再删除要素。代码如下:

FeatureDefn oDefn = oLayer.GetLayerDefn();
Feature oFeature = new Feature(oDefn);
oLayer.CreateFeature(oFeature);
oLayer.SyncToDisk();
oDS.SyncToDisk();
oLayer.DeleteFeature(0);

但是采用函数deleteFeature后发现,要素并没有被删除,于是在网上找各种资料,发现再调用该方法后,必须加上一句重要的代码:

oDS.ExecuteSQL("REPACK "+oLayer.GetName(),null,"");

,方可解决问题。
最终完整的代码如下:

ogr.RegisterAll();
// 为了支持中文路径,请添加下面这句代码
gdal.SetConfigOption("GDAL_FILENAME_IS_UTF8", "YES");
String newFilePath = "完成的图层名称";
String strDriverName = "ESRI Shapefile";
org.gdal.ogr.Driver oDriver = ogr.GetDriverByName(strDriverName);
if (oDriver == null) {
    throw new CreateLayerException(newFilePath + " 生成失败\n");
}
DataSource oDS = oDriver.CreateDataSource(newFilePath, null);
if (oDS == null) {
    throw new CreateLayerException("文件【" + newFilePath + "】打开失败\n");
}

Layer oLayer = oDS.CreateLayer("parking", null,abstractLayer.getLayerType(), null);
if (oLayer == null) {
    throw new CreateLayerException("创建图层失败");
}
FieldDefn oFieldID = new FieldDefn("id", ogr.OFTString);
oLayer.CreateField(oFieldID, 1);
FeatureDefn oDefn = oLayer.GetLayerDefn();
Feature oFeature = new Feature(oDefn);
oLayer.CreateFeature(oFeature);
oLayer.SyncToDisk();
oDS.SyncToDisk();
oLayer.DeleteFeature(0);
oDS.ExecuteSQL("REPACK "+oLayer.GetName(),null,"");

转载自:https://blog.csdn.net/u013177446/article/details/55212001