【Java OGR開發】如何建立空的向量shapfile檔案
阿新 • • 發佈:2019-02-11
目的:使用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,"");