20.基于java-geotools对shp的创建及增删改

该博客主要介绍了使用Java结合ArcGIS对shp文件进行数据操作。涵盖创建shp文件并添加数据、在已有shp文件中新增数据、更新shp文件数据以及移除shp文件数据等内容,每个操作都包含数据准备和具体执行步骤。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

查询

创建shp

数据准备

let param={code: "utf-8", 
        datalist: [ 
        {name:"地方",type:0,heigh:2.5,geom:"POINT(109.588 34.645)"}, 
        {name:"煽动反",type:2,heigh:3.2,geom:"POINT(109.588 34.645)"} 
        ], 
        filepath: "D:gisdata/gp/aaa/sx_test.shp", 
        geomfiled: "geom", 
        keylist: [ 
        { 
            filedname: "name", 
            type: "string" 
        },{ 
            filedname: "type", 
            type: "int" 
        },{ 
            filedname: "heigh", 
            type: "double" 
        } 
        ], 
        type: "Point" 
        }

shp文件创建及添加数据

 /**
* 生成shape文件
*
* @param shpPath  生成shape文件路径(包含文件名称) filepath
* @param encode   编码 code
* @param geoType  图幅类型,Point和Rolygon
* @param shpKey   data中图幅的key  geomfiled
* @param attrKeys 属性key集合 keylist
* @param data     图幅和属性集合 datalist
*/
public  void write2Shape(String shpPath, String encode, String geoType, String shpKey, List<ShpFiled> attrKeys, List<Map<String, Object>> data) {
       WKTReader reader = new WKTReader();
   try {
       //创建shape文件对象
       File file = new File(shpPath);
       Map<String, Serializable> params = new HashMap<>();
       params.put(ShapefileDataStoreFactory.URLP.key, file.toURI().toURL());
       ShapefileDataStore ds = (ShapefileDataStore) new ShapefileDataStoreFactory().createNewDataStore(params);

       //定义图形信息和属性信息
       SimpleFeatureTypeBuilder tb = new SimpleFeatureTypeBuilder();
       tb.setCRS(DefaultGeographicCRS.WGS84);
       tb.setName("sx_test");
       tb.add("the_geom", getClass(geoType));
       for (ShpFiled field : attrKeys) {
           tb.add(field.getFiledname().toUpperCase(), getClass(field.getType()));
       }
       ds.createSchema(tb.buildFeatureType());
       //设置编码
       Charset charset = Charset.forName(encode);
       ds.setCharset(charset);
       
       //设置Writer
       FeatureWriter<SimpleFeatureType, SimpleFeature> writer = ds.getFeatureWriter(ds.getTypeNames()[0], Transaction.AUTO_COMMIT);
       //    写入文件信息
       for (int i = 0; i < data.size(); i++) {
   
           SimpleFeature feature = writer.next();
           Map<String, Object> row = data.get(i);
           
           
           Geometry geom = reader.read(row.get(shpKey).toString());
           feature.setAttribute("the_geom", geom);
           for (ShpFiled field : attrKeys) {
               if (row.get(field.getFiledname()) != null) {
                   feature.setAttribute(field.getFiledname().toUpperCase(), row.get(field.getFiledname()));
               } else {
                   feature.setAttribute(field.getFiledname().toUpperCase(), null);
               }
           }
           
           
       }
       writer.write();
       writer.close();
       ds.dispose();

       //添加到压缩文件
       //zipShapeFile(shpPath);
   } catch (IOException e) {
       e.printStackTrace();
   }catch (Exception e) {
       e.printStackTrace();
   }
}

shp新增数据

数据准备

{filename:"D:\gisdata\gp\sx_qxzd.shp",list:[{'name':'dfs','geom': 'POINT(108.555 34.645)'}]}

开始新增

/**
	 * 向shp文件添加数据
	 * 
	 * @param path 文件路径
	 * @param datalist 空间及属性数据
	 */
	public static void addFeature(String path, List<Map<String, Object>> datalist,String code) {

		ShapefileDataStore dataStore = null;
		File file = new File(path);
		try {
			dataStore = new ShapefileDataStore(file.toURL());
			Charset charset = Charset.forName(code);
			dataStore.setCharset(charset);
			String typeName = dataStore.getTypeNames()[0];

			SimpleFeatureStore store = (SimpleFeatureStore) dataStore.getFeatureSource(typeName);
			SimpleFeatureType featureType = store.getSchema();
			// 获取字段列表
			List<String> fileds = getFileds(featureType);
			// System.out.println(fileds.toString());
			// 创建Features

			List<SimpleFeature> list = new ArrayList<SimpleFeature>();
			WKTReader reader = new WKTReader();
			for (Map<String, Object> data : datalist) {
				SimpleFeatureBuilder build = new SimpleFeatureBuilder(featureType);
				if (data.get("geom") != null) {
					Geometry geometry = reader.read(data.get("geom").toString());
					build.add(geometry);
				}else {
					build.add(null);
				}
				for (String filed : fileds) {
					Object object = data.get(filed);
					build.add(object);
				}
				SimpleFeature feature = build.buildFeature(null);
				list.add(feature);
			}

			SimpleFeatureCollection collection = new ListFeatureCollection(featureType, list);

			Transaction transaction = new DefaultTransaction("Adding");

			store.setTransaction(transaction);

			try {
				store.addFeatures(collection);
				transaction.commit();
				System.out.println("============addFeature=====done=====");

			} catch (Exception eek) {
				eek.printStackTrace();
				transaction.rollback();
			}
		} catch (MalformedURLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

shp更新数据

数据准备

{filename必填:"D:\\gisdata\\gp\\sx_qxzd.shp",list:[{'name':'dfs','geom': 'POINT(108.555 34.645)'},where:'FID_1=425']}

开始更新

/**
	 * 更新shp文件数据
	 * 
	 * @param path 文件路径
	 * @param datalist 空间及属性数据
	 */
	public static void updateFeature(String path, List<Map<String, Object>> datalist,String code) {
		ShapefileDataStore dataStore = null;
		File file = new File(path);
		Transaction transaction = new DefaultTransaction("handle");
		try {
			dataStore = new ShapefileDataStore(file.toURL());
			Charset charset = Charset.forName(code);
			dataStore.setCharset(charset);
			String typeName = dataStore.getTypeNames()[0];
			SimpleFeatureStore store = (SimpleFeatureStore) dataStore.getFeatureSource(typeName);

			// 获取字段列表
			SimpleFeatureType featureType = store.getSchema();
			List<String> fileds = getFileds(featureType);
			store.setTransaction(transaction);
			WKTReader reader = new WKTReader();
			for (Map<String, Object> data : datalist) {
				
				Filter filter = null;
				if (data.get("where") != null) {
					filter = ECQL.toFilter(data.get("where").toString());
				}

				Object[] objs = new Object[] {};
				String[] str = new String[] {};
				if (data.get("geom") != null) {
					Geometry geometry = reader.read(data.get("geom").toString());
					str = add(str, "the_geom");
					objs = add(objs, geometry);

				}
				for (String stri : fileds) {
					if (data.get(stri) != null) {

						str = add(str, stri);
						objs = add(objs, data.get(stri));
					}
				}
				store.modifyFeatures(str, objs, filter);
			}

			transaction.commit();
			System.out.println("========updateFeature====end====");
		} catch (Exception eek) {
			eek.printStackTrace();
			try {
				transaction.rollback();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

		}

	}

shp移除数据

数据准备

{filename:"D:\gisdata\gp\sx_qxzd.shp",ids:[256],filed:"id"}

开始移除

/**
	 * 移除shp中的数据
	 * @param path 文件路径
	 * @param ids 字段值数组
	 * @param filed 字段名
	 */
	public static void removeFeature(String path, List<String>ids,String filed,String code){
		ShapefileDataStore dataStore = null;
		File file = new File(path);
		Transaction transaction = new DefaultTransaction("handle");
		try {
			dataStore = new ShapefileDataStore(file.toURL());
			Charset charset = Charset.forName(code);
			dataStore.setCharset(charset);
			String typeName = dataStore.getTypeNames()[0];
			SimpleFeatureStore store = (SimpleFeatureStore) dataStore.getFeatureSource(typeName);    
			store.setTransaction(transaction);      
			    
		    Filter filter = null;
		    if(ids.size()>0) {
		    	String join = filed +" in ("+StringUtils.join(ids,",")+")";
		    	System.out.println(join);
		    	filter = ECQL.toFilter(join);
		    }
		    if(filter!=null) {
		    	
		    	store.removeFeatures(filter);
		    	transaction.commit();            
		    	System.out.println("======removeFeature== done ========");
		    }
		 
		} catch (Exception eek) {
			eek.printStackTrace();
			try {
				transaction.rollback();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
	
		}
    
	}
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

紫雪giser

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值