geotools系列2-读取postgis 博客分类: GIS geotoolspostgisgisjava
程序员文章站
2024-02-25 08:45:58
...
上期我介绍了geotools读取shp文件的事例 (geotools系列1-读取shp文件),本次说明读取读取postgis里表数据的代码,依旧是读取数据打印出来展示。
1、环境,maven依赖等,参见上次 geotools系列1-读取shp文件 。
2、直接上java代码
package com.jjxliu.geotools.geotools_t1; import java.io.IOException; import java.util.HashMap; import java.util.Map; import org.geotools.data.DataStoreFinder; import org.geotools.data.simple.SimpleFeatureCollection; import org.geotools.data.simple.SimpleFeatureIterator; import org.geotools.data.simple.SimpleFeatureSource; import org.geotools.jdbc.JDBCDataStore; import org.opengis.feature.simple.SimpleFeature; import org.opengis.filter.Filter; public class TestPostgis { public static SimpleFeatureCollection readPostgisTable(String host , int port , String user , String pass , String dbname, String schema , String tablename ){ return readPostgisTable(host, port, user, pass, dbname, schema, tablename , null); } public static SimpleFeatureCollection readPostgisTable(String host , int port , String user , String pass , String dbname, String schema , String tablename , Filter filter){ Map<String, Object> params = new HashMap<>(); params.put("dbtype", "postgis"); params.put("host", host); params.put("port", port); params.put("schema", schema); params.put("database", dbname); params.put("user", user); params.put("passwd", pass); try { JDBCDataStore dataStore = (JDBCDataStore) DataStoreFinder.getDataStore(params); return readDatastore(dataStore, tablename, filter); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return null; } public static SimpleFeatureCollection readDatastore(JDBCDataStore store ,String typeName , Filter filter){ try { SimpleFeatureSource featureSource = store.getFeatureSource(typeName); return filter != null ? featureSource.getFeatures(filter) : featureSource.getFeatures(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return null; } }
3、测试
public static void main(String[] args) { String host = "127.0.0.1"; String schema = "public" ; String database = "lyf" ; String user = "lyf" ; String pass = "lyf123" ; String tablename = "cell" ; int port = 6666; //读取 SimpleFeatureCollection colls1 = readPostgisTable(host, port, user, pass, database, schema, tablename); if(colls1 == null){ System.out.println("请检查参数,确保jdbc连接正常以及表存在."); return; } //拿到所有features SimpleFeatureIterator iters = colls1.features(); //遍历打印 while(iters.hasNext()){ SimpleFeature sf = iters.next(); System.out.println(sf.getID() + " , " + sf.getAttributes()); } }
结果贴图:
附件有完整代码。