/**
* 生成shape文件
*
* @param shpPath 生成shape文件路径(包含文件名称)
* @param encode 编码
* @param geoType 图幅类型,Point和Rolygon
* @param geoms 图幅集合
*/
public static void write2Shape(String shpPath, String encode, String geoType, List<Geometry> geoms) {
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("shapefile");
if ("Polygon".equals(geoType)) {
tb.add("the_geom", Polygon.class);
} else if ("MultiPolygon".equals(geoType)) {
tb.add("the_geom", MultiPolygon.class);
} else if ("Point".equals(geoType)) {
tb.add("the_geom", Point.class);
} else if ("MultiPoint".equals(geoType)) {
tb.add("the_geom", MultiPoint.class);
} else if ("LineString".equals(geoType)) {
tb.add("the_geom", LineString.class);
} else if ("MultiLineString".equals(geoType)) {
tb.add("the_geom", MultiLineString.class);
} else {
throw new Exception("Geometry中没有该类型:" + geoType);
}
ds.createSchema(tb.buildFeatureType());
//设置编码
ds.setCharset(Charset.forName(encode));
//设置Writer
FeatureWriter<SimpleFeatureType, SimpleFeature> writer = ds.getFeatureWriter(ds.getTypeNames()[0], Transaction.AUTO_COMMIT);
for (Geometry geom : geoms) {
SimpleFeature feature = writer.next();
feature.setAttribute("the_geom", geom);
}
writer.write();
writer.close();
ds.dispose();
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) throws Exception {
List<String> list = new ArrayList<>();
list.add("POLYGON ((116.21278950384274 39.90557982319698, 116.21177234433465 39.90610963061354, 116.21106912279264 39.90264172209895, 116.21399502548638 39.902612822554126, 116.21629305278306 39.905011479365406, 116.21278950384274 39.90557982319698))");
list.add("POLYGON((113.38185597038 34.54828048706,113.38224220848 34.548355588913,113.38249970055 34.548108825684,113.38237095451 34.54787279129,113.38208127594 34.547786960602,113.38185597038 34.54828048706))");
List<Geometry> geometryList = new ArrayList<>();
for (String str : list) {
Geometry geom = wktToGeom(str);
geometryList.add(geom);
}
String url = "F://tmp//ceshi2222.shp";
ShapeUtil.write2Shape(url, "utf-8", "Polygon", geometryList);
}
说几个重要的类:
**DataStore:**访问和存储矢量格式空间数据的引擎,对应关系数据库中database的概念,可以用来更新 ,删除,获取SimpleFeatureType(类比数据库中一张具体表)
**FeatureSource:**与DataStore相比,粒度更细,内部操作都是针对这张表的。
**FeatureStore:**子接口,对数据本身进行设置。
**SimpleFeature:**类比数据库中一条记录,与SimpleFeatureType进行了绑定。
**SimpleFeatureType:**对SimpleFeature进行数据结构约束,类比关系数据库的表结构。
**FeatureCollection:**存储Feature对象的集合类,注意两点:1.其迭代器使用完毕必须显示关闭,2.存储在同一个FeatureCollection中的对象具有相同的SimpleFeatureType。