Geotools处理shape文件
Posted 行走于代码中
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Geotools处理shape文件相关的知识,希望对你有一定的参考价值。
Geotools,shape
shape文件结构
- filename.shp: shapes
- filename.shx: 索引文件
- filename.dbf: 结构化数据文件
- filename.qix: 空间索引文件
- filename.fix: fid索引文件
- filename.sld: 样式文件
依赖
<dependency>
<groupId>org.geotools</groupId>
<artifactId>gt-main</artifactId>
<version>27.2</version>
</dependency>
<dependency>
<groupId>org.geotools</groupId>
<artifactId>gt-shapefile</artifactId>
<version>27.2</version>
</dependency>
创建连接
连接参数
Parameter | required | Description |
---|---|---|
url | true | .shp文件的url |
namespace | false | FeatureType的URI |
create spatial index | false | 是否创建空间索引,默认true |
charset | false | 解码DBF文件的编码,默认ISO_8859_1 |
timezone | false | 解析DBF文件时间的时区 |
memory mapped buffer | false | 内存映射,默认false |
cache and reuse memory maps | false | 使用内存映射时,缓存并重用,默认true |
enable spatial index | false | 是否使用空间索引,默认true |
代码示例
/**
*
* 创建shape文件
*
* */
FileDataStoreFactorySpi factory = new ShapefileDataStoreFactory();
//新建文件
File file = new File("my.shp");
//datastore
Map<String, Object> params = new HashMap<>();
params.put("url", file.toURI().toURL());
params.put("create spatial index", Boolean.TRUE);
DataStore dataStore = factory.createNewDataStore(params);
//Feature数据定义
SimpleFeatureTypeBuilder typeBuilder = new SimpleFeatureTypeBuilder();
//图层名
typeBuilder.setName("myLayer");
//空间坐标
typeBuilder.setCRS(CRS.decode("EPSG:4490"));
typeBuilder.add("the_geom", Point.class);
//普通属性字段
typeBuilder.add("id", String.class);
typeBuilder.length(10).add("name", String.class);//字段长度
typeBuilder.add("number",Integer.class);
typeBuilder.add("double",Double.class);
typeBuilder.add("time",Date.class);
SimpleFeatureType featureType = typeBuilder.buildFeatureType();
//创建feature定义到shape
dataStore.createSchema(featureType);
/**
* 写数据到shape文件
*
* */
//shape中feature定义
Map<String, Object> params = new HashMap<>();
params.put("url", file.toURI().toURL());
DataStore dataStore2 = DataStoreFinder.getDataStore(params);
String typeName = dataStore2.getTypeNames()[0];
SimpleFeatureSource featureSource = dataStore2.getFeatureSource(typeName);
SimpleFeatureType schema = featureSource.getSchema();
//事务处理
Transaction transaction = new DefaultTransaction("create");
if (featureSource instanceof SimpleFeatureStore)
SimpleFeatureStore featureStore = (SimpleFeatureStore) featureSource;
//创建一条数据 feature
List<SimpleFeature> features = new ArrayList<>();
GeometryFactory geometryFactory = JTSFactoryFinder.getGeometryFactory();
SimpleFeatureBuilder featureBuilder = new SimpleFeatureBuilder(schema);
Point point = geometryFactory.createPoint(new Coordinate(106.69563874,29.563694210810283));
featureBuilder.set("the_geom",point);
featureBuilder.set("id","id1");
featureBuilder.set("name","name1");
featureBuilder.set("number1",100);
featureBuilder.set("number2",66.0);
featureBuilder.set("time",new Date());
SimpleFeature feature = featureBuilder.buildFeature(null);
features.add(feature);
SimpleFeatureCollection collection = new ListFeatureCollection(schema, features);
featureStore.setTransaction(transaction);
try
//写入shape中
featureStore.addFeatures(collection);
transaction.commit();
catch (Exception e)
e.printStackTrace();
transaction.rollback();
finally
transaction.close();
else
System.out.println("写入失败");
/**
* 读取shape文件数据
*
* */
DataStore dataStore3 = new ShapefileDataStore(file.toURI().toURL());
String typeName = dataStore3.getTypeNames()[0];
FeatureSource<SimpleFeatureType, SimpleFeature> source =dataStore3.getFeatureSource(typeName);
Filter filter = Filter.INCLUDE;
FeatureCollection<SimpleFeatureType, SimpleFeature> collection = source.getFeatures(filter);
try (FeatureIterator<SimpleFeature> features = collection.features())
//features必须关闭,否则会造成内存泄漏
while (features.hasNext())
SimpleFeature feature = features.next();
feature.getProperties().stream().peek(e-> System.out.println(e.getName().getLocalPart() + " = " + e.getValue()));
java geotools
参考技术A java geotools是什么,让我们一起了解一下?Geotools是一个java类库,提供了很多的标准类和方法来处理空间数据,同时这个类库是构建在OGC标准之上的,是OGC思想的一种实现。使用Java语言和面向对象方法时,按照功能划分模块,结构清晰。
它的核心特点是什么?
1、为空间概念和数据结构定义了很多的接口。
2、通过JTS类库集成了对几何拓扑的支持。
3、通过使用OGC过滤编码规范可以对属性和空间要素过滤。
4、对于数据访问API,支持要素访问、事务支持和线程间锁定。
5、可以访问多种格式的数据和空间数据库。
6、支持多种坐标参考系统和及其转换。
7、可以和扩展的地图投影一同工作。
8、可以按照空间和非空间属性来过滤和分析数据。
9、一种无状态的,耗低内存的渲染机制,尤其在服务端环境下。
10、通过复杂的样式(SLD)来组成和展现地图。
实战操作:
java如何用geotools类库读取shapefile?
shapefile是esri公司最先搞出来的,那么arcgis应该是有相关的类库的吧?好像找不到?我问过搞移动端的同事,arcgis for android确有处理shapefile的类库,处理起来易如反掌。
但是,在WEB系统,服务器端从shapefile读出数据,最终是要在前端浏览器中展示,像我们目前在建的项目,就是要用arcgis for js来展示这些数据,而安卓系统类似CS项目,有很大的不同。最大的不同,WEB系统中,数据要以JSON的形式给前端,这样才好处理。 import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONObject; import org.geotools.data.FileDataStore; import org.geotools.data.FileDataStoreFinder; import org.geotools.data.shapefile.ShapefileDataStore; import org.geotools.data.shapefile.dbf.DbaseFileHeader; import org.geotools.data.shapefile.dbf.DbaseFileReader; import org.geotools.data.shapefile.files.ShpFiles; import org.geotools.data.simple.SimpleFeatureCollection; import org.geotools.data.simple.SimpleFeatureIterator; import org.geotools.data.simple.SimpleFeatureSource; import org.geotools.geojson.feature.FeatureJSON; import org.geotools.geometry.jts.ReferencedEnvelope; import org.locationtech.jts.geom.Coordinate; import org.locationtech.jts.geom.Geometry; import org.opengis.feature.Property; import org.opengis.feature.simple.SimpleFeature; import org.opengis.feature.simple.SimpleFeatureType; import org.opengis.referencing.FactoryException; import org.opengis.referencing.crs.CoordinateReferenceSystem; import org.opengis.referencing.operation.TransformException; import java.io.*; import java.nio.charset.Charset; import java.util.*; /* shapefile操作类 */ public class ShapefileHelper public static Object read(String path) throws IOException /* 参数path就是shp文件的完整路径,如:E:\\蟠桃会资源清查\\调查图斑.shp 系统会自动检查同一个目录下有没有其他相关文件,有的话会一并读出, 相关文件的路径无须给出 .shp 存储地理形状和位置信息 .dbf 存储属性信息 .shx 索引文件 .prj 坐标系 .cpg 字符编码,如UTF-8 读取出来的结果类型为 List */ List list = new ArrayList (); File file = getFile(path); if (file == null) return list; String charset = getCharSet(path); FileDataStore store = FileDataStoreFinder.getDataStore(file); ((ShapefileDataStore)store).setCharset(Charset.forName(charset)); SimpleFeatureSource featureSource = store.getFeatureSource(); SimpleFeatureCollection collection = featureSource.getFeatures(); SimpleFeatureIterator features = collection.features(); while (features.hasNext()) Map item = new HashMap(); SimpleFeature f = features.next(); Collection p = f.getProperties(); Iterator it = p.iterator(); while (it.hasNext()) Property pro = it.next(); String field = pro.getName().toString(); field = field.equals("the_geom") ? "wkt" : field; String value = pro.getValue().toString(); item.put(field, value); list.add(item); return list; private static File getFile(String path) File file = new File(path); if (file == null) System.out.println("找不到路径:" + path); return file; /* 获取shapefile字符编码 如果存在.cpg文件,则从中读取,否则默认为UTF-8 */ private static String getCharSet(String path) String charset = "UTF-8"; int p = path.lastIndexOf("."); String cpg = path.substring(0,p) + ".cpg"; File file = getFile(cpg); if(file != null) RandomAccessFile raf = null; try raf = new RandomAccessFile(cpg, "r"); charset = raf.readLine(); raf.close(); catch (FileNotFoundException e) e.printStackTrace(); catch (IOException e) e.printStackTrace(); return charset;
以上是关于Geotools处理shape文件的主要内容,如果未能解决你的问题,请参考以下文章
GeoJson的生成与解析,JSON解析,Java读写geojson,geotools读取shp文件,Geotools中Geometry对象与GeoJson的相互转换