JAVA用geotools读写shape格式文件
转自:http://toplchx.iteye.com/blog/1335007
JAVA用geotools读写shape格式文件 (对应geotools版本:2.7.2)
(后面添加对应geotools 10.0版本的写法)
读shape文件。
shape格式文件最少包含3个文件,他们的后缀是:.shp, .dbf, .shx。
.shp存储地理形状和位置信息,.dbf存储属性信息,.shx是索引文件。
单独读取DBF文件
public void readDBF(String path) {
- DbaseFileReader reader = null;
- try {
- reader = new DbaseFileReader(new ShpFiles(path), false, Charset.forName("GBK"));
- DbaseFileHeader header = reader.getHeader();
- int numFields = header.getNumFields();
- //迭代读取记录
- while (reader.hasNext()) {
- try {
- Object[] entry = reader.readEntry();
- for (int i=0; i<numFields; i++) {
- String title = header.getFieldName(i);
- Object value = entry[i];
- System.out.println(title+"="+value);
- }
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- } catch (Exception e) {
- e.printStackTrace();
- } finally {
- if (reader != null) {
- //关闭
- try {reader.close();} catch (Exception e) {}
- }
- }
- }
读取3个文件,以point为例:
public void readSHP(String path) {
- ShapefileDataStore shpDataStore = null;
- try{
- shpDataStore = new ShapefileDataStore(new File(path).toURI().toURL());
- shpDataStore.setStringCharset(Charset.forName("GBK"));
- String typeName = shpDataStore.getTypeNames()[0];
- FeatureSource<SimpleFeatureType, SimpleFeature> featureSource = null;
- featureSource = (FeatureSource<SimpleFeatureType, SimpleFeature>)shpDataStore.getFeatureSource(typeName);
- FeatureCollection<SimpleFeatureType, SimpleFeature> result = featureSource.getFeatures();
- System.out.println(result.size());
- FeatureIterator<SimpleFeature> itertor = result.features();
- while(itertor.hasNext()){
- SimpleFeature feature = itertor.next();
- Collection<Property> p = feature.getProperties();
- Iterator<Property> it = p.iterator();
- while(it.hasNext()) {
- Property pro = it.next();
- if (pro.getValue() instanceof Point) {
- System.out.println("PointX = " + ((Point)(pro.getValue())).getX());
- System.out.println("PointY = " + ((Point)(pro.getValue())).getY());
- } else {
- System.out.println(pro.getName() + " = " + pro.getValue());
- }
- }
- }
- itertor.close();
- } catch (MalformedURLException e) {
- e.printStackTrace();
- } catch(IOException e) { e.printStackTrace(); }
- }
写shape文件,以point为例:
- public static void main(String[] args) {
- try{
- //定义属性
- final SimpleFeatureType TYPE = DataUtilities.createType("Location",
- "location:Point," + // <- the geometry attribute: Point type
- "POIID:String," + // <- a String attribute
- "MESHID:String," + // a number attribute
- "OWNER:String"
- );
- SimpleFeatureCollection collection = FeatureCollections.newCollection();
- GeometryFactory geometryFactory = new GeometryFactory();
- SimpleFeatureBuilder featureBuilder = new SimpleFeatureBuilder(TYPE);
- double latitude = Double.parseDouble("116.123456789");
- double longitude = Double.parseDouble("39.120001");
- String POIID = "2050003092";
- String MESHID = "0";
- String OWNER = "340881";
- /* Longitude (= x coord) first ! */
- Point point = geometryFactory.createPoint(new Coordinate(longitude, latitude));
- Object[] obj = {point, POIID, MESHID, OWNER};
- SimpleFeature feature = featureBuilder.buildFeature(null, obj);
- collection.add(feature);
- feature = featureBuilder.buildFeature(null, obj);
- collection.add(feature);
- File newFile = new File("D:/newPoi.shp");
- ShapefileDataStoreFactory dataStoreFactory = new ShapefileDataStoreFactory();
- Map<String, Serializable> params = new HashMap<String, Serializable>();
- params.put("url", newFile.toURI().toURL());
- params.put("create spatial index", Boolean.TRUE);
- ShapefileDataStore newDataStore = (ShapefileDataStore) dataStoreFactory.createNewDataStore(params);
- newDataStore.createSchema(TYPE);
- newDataStore.forceSchemaCRS(DefaultGeographicCRS.WGS84);
- Transaction transaction = new DefaultTransaction("create");
- String typeName = newDataStore.getTypeNames()[0];
- SimpleFeatureSource featureSource = newDataStore.getFeatureSource(typeName);
- if (featureSource instanceof SimpleFeatureStore) {
- SimpleFeatureStore featureStore = (SimpleFeatureStore) featureSource;
- featureStore.setTransaction(transaction);
- try {
- featureStore.addFeatures(collection);
- transaction.commit();
- } catch (Exception problem) {
- problem.printStackTrace();
- transaction.rollback();
- } finally {
- transaction.close();
- }
- } else {
- System.out.println(typeName + " does not support read/write access");
- }
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
以下代码对应geotools10.0版本
一、读shp文件(图形信息+属性信息)的写法:
- import java.io.File;
- import java.nio.charset.Charset;
- import java.util.Iterator;
- import org.geotools.data.shapefile.ShapefileDataStore;
- import org.geotools.data.shapefile.ShapefileDataStoreFactory;
- import org.geotools.data.simple.SimpleFeatureIterator;
- import org.geotools.data.simple.SimpleFeatureSource;
- import org.opengis.feature.Property;
- import org.opengis.feature.simple.SimpleFeature;
- public class ShpNew {
- public static void main(String[] args) {
- ShapefileDataStoreFactory dataStoreFactory = new ShapefileDataStoreFactory();
- try {
- ShapefileDataStore sds = (ShapefileDataStore)dataStoreFactory.createDataStore(new File("D:\\work\\shpdir\\Poi.shp").toURI().toURL());
- sds.setCharset(Charset.forName("GBK"));
- SimpleFeatureSource featureSource = sds.getFeatureSource();
- SimpleFeatureIterator itertor = featureSource.getFeatures().features();
- while(itertor.hasNext()) {
- SimpleFeature feature = itertor.next();
- Iterator<Property> it = feature.getProperties().iterator();
- while(it.hasNext()) {
- Property pro = it.next();
- System.out.println(pro);
- }
- }
- itertor.close();
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- }
二、读图形信息
- try {
- ShpFiles sf = new ShpFiles("D:\\Poi.shp");
- ShapefileReader r = new ShapefileReader( sf, false, false, new GeometryFactory() );
- while (r.hasNext()) {
- Geometry shape = (Geometry) r.nextRecord().shape(); //com.vividsolutions.jts.geom.Geometry;
- System.out.println(shape.toString());
- }
- r.close();
- } catch (Exception e) {
- e.printStackTrace();
- }
三、读dbf文件
- public void readDBF() {
- try {
- FileChannel in = new FileInputStream("D:\\Poi.dbf").getChannel();
- DbaseFileReader dbfReader = new DbaseFileReader(in, false, Charset.forName("GBK"));
- DbaseFileHeader header = dbfReader.getHeader();
- int fields = header.getNumFields();
- while ( dbfReader.hasNext() ){
- DbaseFileReader.Row row = dbfReader.readRow();
- // System.out.println(row.toString());
- for (int i=0; i<fields; i++) {
- System.out.println(header.getFieldName(i) + " : " + row.read(i));
- }
- }
- dbfReader.close();
- in.close();
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
四、写shape文件
- public void write(String filepath) {
- try {
- //创建shape文件对象
- File file = new File(filepath);
- Map<String, Serializable> params = new HashMap<String, Serializable>();
- 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");
- tb.add("the_geom", Point.class);
- tb.add("POIID", Long.class);
- tb.add("NAMEC", String.class);
- ds.createSchema(tb.buildFeatureType());
- ds.setCharset(Charset.forName("GBK"));
- //设置Writer
- FeatureWriter<SimpleFeatureType, SimpleFeature> writer = ds.getFeatureWriter(ds.getTypeNames()[0], Transaction.AUTO_COMMIT);
- //写下一条
- SimpleFeature feature = writer.next();
- feature.setAttribute("the_geom", new GeometryFactory().createPoint(new Coordinate(116.123, 39.345)));
- feature.setAttribute("POIID", 1234567890l);
- feature.setAttribute("NAMEC", "某兴趣点1");
- feature = writer.next();
- feature.setAttribute("the_geom", new GeometryFactory().createPoint(new Coordinate(116.456, 39.678)));
- feature.setAttribute("POIID", 1234567891l);
- feature.setAttribute("NAMEC", "某兴趣点2");
- writer.write();
- writer.close();
- ds.dispose();
- //读取刚写完shape文件的图形信息
- ShpFiles shpFiles = new ShpFiles(filepath);
- ShapefileReader reader = new ShapefileReader(shpFiles, false, true, new GeometryFactory(), false);
- try {
- while (reader.hasNext()) {
- System.out.println(reader.nextRecord().shape());
- }
- } finally {
- reader.close();
- }
- } catch (Exception e) { }
- }
五、由源shape文件创建新的shape文件
- public void transShape(String srcfilepath, String destfilepath) {
- try {
- //源shape文件
- ShapefileDataStore shapeDS = (ShapefileDataStore) new ShapefileDataStoreFactory().createDataStore(new File(srcfilepath).toURI().toURL());
- //创建目标shape文件对象
- Map<String, Serializable> params = new HashMap<String, Serializable>();
- FileDataStoreFactorySpi factory = new ShapefileDataStoreFactory();
- params.put(ShapefileDataStoreFactory.URLP.key, new File(destfilepath).toURI().toURL());
- ShapefileDataStore ds = (ShapefileDataStore) factory.createNewDataStore(params);
- // 设置属性
- SimpleFeatureSource fs = shapeDS.getFeatureSource(shapeDS.getTypeNames()[0]);
- //下面这行还有其他写法,根据源shape文件的simpleFeatureType可以不用retype,而直接用fs.getSchema设置
- ds.createSchema(SimpleFeatureTypeBuilder.retype(fs.getSchema(), DefaultGeographicCRS.WGS84));
- //设置writer
- FeatureWriter<SimpleFeatureType, SimpleFeature> writer = ds.getFeatureWriter(ds.getTypeNames()[0], Transaction.AUTO_COMMIT);
- //写记录
- SimpleFeatureIterator it = fs.getFeatures().features();
- try {
- while (it.hasNext()) {
- SimpleFeature f = it.next();
- SimpleFeature fNew = writer.next();
- fNew.setAttributes(f.getAttributes());
- writer.write();
- }
- } finally {
- it.close();
- }
- writer.close();
- ds.dispose();
- shapeDS.dispose();
- } catch (Exception e) { e.printStackTrace(); }
- }
JAVA用geotools读写shape格式文件的更多相关文章
- JAVA用geotools读取shape格式文件
Shapefile属于一种矢量图形格式,它能够保存几何图形的位置及相关属性.但这种格式没法存储地理数据的拓扑信息. 其中,要组成一个Shapefile,有三个文件是必不可少的,它们分别是". ...
- 使用Spark读写CSV格式文件(转)
原文链接:使用Spark读写CSV格式文件 CSV格式的文件也称为逗号分隔值(Comma-Separated Values,CSV,有时也称为字符分隔值,因为分隔字符也可以不是逗号.在本文中的CSV格 ...
- Java使用Geotools读取shape矢量数据
作为GIS开发者而言,矢量数据是我们经常要用到的,而shape数据是矢量数据中最常用的格式,因此解析shape数据也是作为GIS软件开发人员必备的基础技能,而GeoTools无疑是Java最好用来处理 ...
- java 调用OpenOffice将word格式文件转换为pdf格式
一:环境搭建 OpenOffice 下载地址http://www.openoffice.org/ JodConverter 下载地址http://sourceforge.net/projects/jo ...
- 如何用python读写CSV 格式文件
工作中经常会碰到读写CSV文件的情况.记录下,方便自己以后查询并与大家一起分享: 写CSV文件方法一: import csv #导入CSV with open("D:\eg ...
- python利用lxml读写xml格式文件
之前在转换数据集格式的时候需要将json转换到xml文件,用lxml包进行操作非常方便. 1. 写xml文件 a) 用etree和objectify from lxml import etree, o ...
- java使用jdom生成xml格式文件
本文生成xml使用的工具是jdom.jar,下载地址如下: 链接:https://eyun.baidu.com/s/3slyHgnj 密码:0TXF 生成之后的文档格式类型,就如上面的图片一样,简单吧 ...
- 使用csv模块读写csv格式文件
import csv class HandleCsv: ''' csv文件处理类 ''' def __init__(self, filename): ''' 构造器 :param filename: ...
- 使用JAVA读写Properties属性文件
使用JAVA读写Properties属性文件 Properties属性文件在JAVA应用程序中是经常可以看得见的,也是特别重要的一类文件.它用来配置应用程序的一些信息,不过这些信息一般都是比较少的数 ...
随机推荐
- java编程思想,对象导论
程序设计的本质就是使用编程语言解决某一类具体问题.对问题的定义叫建模,例如定义问题域中的各种名词,动作,结果等.针对具体的问题提出的解决方案叫算法. 面向对象程序设计的挑战之一,就是在问题空间的元素和 ...
- python 自动化之路 day 02
本节内容: 列表.元组操作 字符串操作 1. 列表.元组操作 列表是我们最以后最常用的数据类型之一,通过列表可以对数据实现最方便的存储.修改等操作 定义列表 1 names = ['Alex',&qu ...
- ubuntn svn 安装 配置
参考文章 http://zhan.renren.com/itbegin?gid=3602888498033631485&checked=true 上面的文章说得很详细 sudo apt-ge ...
- jQuery学习教程(2)
由于一件事情打断了我的生活节奏,每天都学习都在托托拉拉,导致很多进度都没有达到自己预期的效果 在上一个章节我学到了环境的搭建,以及对jquery的熟悉.现在开始对其具体进行熟悉了. 一.如何使用选择器 ...
- 测试网站是共享还是独立ip
查看是共享还是独立:http://www.yougetsignal.com/tools/web-sites-on-web-server/ 站长工具:http://tool.webmasterhome. ...
- CSS三角形广告文字
街上经常碰到一些发各类广告传单的,有一次收到一张房地产广告的传单,顺手留下来,看着里面有些广告挺吸引人,同时也想练练自己css技术,故抽空做了一下. 原图某区域如下: 实现上图效果是需要一些想象力的, ...
- php练习3——猜拳游戏,评委打分问题
用户与计算机猜拳 程序caiQuan.html和caiQuan.php: 结果: 评委打分问题,去掉一个最低分和最高分,求平均分,并找出最低分和最高分对应第几个评委, 再找出最佳评委(打分最接近 ...
- 如何查看MySQL中每张表占用的空间大小
如题,找到MySQL中的information_schema表,这张表记录了所有数据库中表的信息,主要字段含义如下: TABLE_SCHEMA : 数据库名 TABLE_NAME:表名 ENGINE: ...
- [转载]如何重装Grub,使其可以引导双系统
引言: GRUB是一个多重操作系统的启动管理器.用来引导不同的系统,如windows,Linux.一般来说要先装Windows,后装Linux,这样grub才能生效(grub存在于linux的安装中) ...
- C的快速趋向实验 -->
今天刚学到C的一个新玩法,非常有意思,叫趋向于,写作“-->”,比如说如果要实现一个倒数的程序,我们可以定义一个变量 counter,然后让它趋向于0... #include <stdio ...