基于Java和GDAL实现的GeoJSON数据读取与入库实践
import org.gdal.ogr.DataSource;
import org.gdal.ogr.Driver;
import org.gdal.ogr.Feature;
import org.gdal.ogr.FeatureDefn;
import org.gdal.ogr.FieldDefn;
import org.gdal.ogr.Geometry;
import org.gdal.ogr.Layer;
import org.gdal.ogr.ogr;
public class GeoJSONReadAndWrite {
public static void main(String[] args) {
// 初始化GDAL库
ogr.RegisterAll();
// 创建GeoJSON数据源
String geoJsonFile = "path/to/your/geojsonfile.geojson";
DataSource ds = ogr.Open(geoJsonFile, 0);
if (ds == null) {
System.out.println("打开GeoJSON文件失败");
return;
}
// 获取层
Layer layer = ds.GetLayerByIndex(0);
if (layer == null) {
System.out.println("获取层失败");
return;
}
// 创建新的数据源
String dbFile = "path/to/your/databasefile.gpkg";
Driver dbDriver = ogr.GetDriverByName("GPKG");
if (dbDriver == null) {
System.out.println("获取数据库驱动失败");
return;
}
// 创建数据源
DataSource dbDs = dbDriver.CreateDataSource(dbFile);
if (dbDs == null) {
System.out.println("创建数据源失败");
return;
}
// 创建图层
FeatureDefn featureDefn = layer.GetLayerDefn();
String layerName = "new_layer";
Layer dbLayer = dbDs.CreateLayer(layerName, featureDefn.GetGeomFieldDefn(0), ogr.wkbNone);
if (dbLayer == null) {
System.out.println("创建图层失败");
return;
}
// 复制字段
for (int i = 0; i < featureDefn.GetFieldCount(); i++) {
FieldDefn fieldDefn = featureDefn.GetFieldDefn(i);
dbLayer.CreateField(fieldDefn);
}
// 复制几何字段
dbLayer.CreateGeomField(new Geometry(ogr.wkbMultiPolygon));
// 复制要素
Feature feature;
while ((feature = layer.GetNextFeature()) != null) {
Feature newFeature = dbLayer.CreateFeature(feature.Clone());
newFeature.SetFID(feature.GetFID());
dbLayer.SetFeature(newFeature);
newFeature.Destroy();
feature.Destroy();
}
// 关闭数据源
dbLayer.SyncToDisk();
dbLayer = null;
dbDs.Destroy();
layer = null;
ds = null;
System.out.println("GeoJSON数据成功
评论已关闭