转自: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) {

  1. DbaseFileReader reader = null;
  2. try {
  3. reader = new DbaseFileReader(new ShpFiles(path), false, Charset.forName("GBK"));
  4. DbaseFileHeader header = reader.getHeader();
  5. int numFields = header.getNumFields();
  6. //迭代读取记录
  7. while (reader.hasNext()) {
  8. try {
  9. Object[] entry = reader.readEntry();
  10. for (int i=0; i<numFields; i++) {
  11. String title = header.getFieldName(i);
  12. Object value = entry[i];
  13. System.out.println(title+"="+value);
  14. }
  15. } catch (Exception e) {
  16. e.printStackTrace();
  17. }
  18. }
  19. } catch (Exception e) {
  20. e.printStackTrace();
  21. } finally {
  22. if (reader != null) {
  23. //关闭
  24. try {reader.close();} catch (Exception e) {}
  25. }
  26. }
  27. }

读取3个文件,以point为例:

public void readSHP(String path) {

  1. ShapefileDataStore shpDataStore = null;
  2. try{
  3. shpDataStore = new ShapefileDataStore(new File(path).toURI().toURL());
  4. shpDataStore.setStringCharset(Charset.forName("GBK"));
  5. String typeName = shpDataStore.getTypeNames()[0];
  6. FeatureSource<SimpleFeatureType, SimpleFeature> featureSource = null;
  7. featureSource = (FeatureSource<SimpleFeatureType, SimpleFeature>)shpDataStore.getFeatureSource(typeName);
  8. FeatureCollection<SimpleFeatureType, SimpleFeature> result = featureSource.getFeatures();
  9. System.out.println(result.size());
  10. FeatureIterator<SimpleFeature> itertor = result.features();
  11. while(itertor.hasNext()){
  12. SimpleFeature feature = itertor.next();
  13. Collection<Property> p = feature.getProperties();
  14. Iterator<Property> it = p.iterator();
  15. while(it.hasNext()) {
  16. Property pro = it.next();
  17. if (pro.getValue() instanceof Point) {
  18. System.out.println("PointX = " + ((Point)(pro.getValue())).getX());
  19. System.out.println("PointY = " + ((Point)(pro.getValue())).getY());
  20. } else {
  21. System.out.println(pro.getName() + " = " + pro.getValue());
  22. }
  23. }
  24. }
  25. itertor.close();
  26. } catch (MalformedURLException e) {
  27. e.printStackTrace();
  28. } catch(IOException e) { e.printStackTrace(); }
  29. }

写shape文件,以point为例:

  1. public static void main(String[] args) {
  2. try{
  3. //定义属性
  4. final SimpleFeatureType TYPE = DataUtilities.createType("Location",
  5. "location:Point," + // <- the geometry attribute: Point type
  6. "POIID:String," + // <- a String attribute
  7. "MESHID:String," + // a number attribute
  8. "OWNER:String"
  9. );
  10. SimpleFeatureCollection collection = FeatureCollections.newCollection();
  11. GeometryFactory geometryFactory = new GeometryFactory();
  12. SimpleFeatureBuilder featureBuilder = new SimpleFeatureBuilder(TYPE);
  13. double latitude = Double.parseDouble("116.123456789");
  14. double longitude = Double.parseDouble("39.120001");
  15. String POIID = "2050003092";
  16. String MESHID = "0";
  17. String OWNER = "340881";
  18. /* Longitude (= x coord) first ! */
  19. Point point = geometryFactory.createPoint(new Coordinate(longitude, latitude));
  20. Object[] obj = {point, POIID, MESHID, OWNER};
  21. SimpleFeature feature = featureBuilder.buildFeature(null, obj);
  22. collection.add(feature);
  23. feature = featureBuilder.buildFeature(null, obj);
  24. collection.add(feature);
  25. File newFile = new File("D:/newPoi.shp");
  26. ShapefileDataStoreFactory dataStoreFactory = new ShapefileDataStoreFactory();
  27. Map<String, Serializable> params = new HashMap<String, Serializable>();
  28. params.put("url", newFile.toURI().toURL());
  29. params.put("create spatial index", Boolean.TRUE);
  30. ShapefileDataStore newDataStore = (ShapefileDataStore) dataStoreFactory.createNewDataStore(params);
  31. newDataStore.createSchema(TYPE);
  32. newDataStore.forceSchemaCRS(DefaultGeographicCRS.WGS84);
  33. Transaction transaction = new DefaultTransaction("create");
  34. String typeName = newDataStore.getTypeNames()[0];
  35. SimpleFeatureSource featureSource = newDataStore.getFeatureSource(typeName);
  36. if (featureSource instanceof SimpleFeatureStore) {
  37. SimpleFeatureStore featureStore = (SimpleFeatureStore) featureSource;
  38. featureStore.setTransaction(transaction);
  39. try {
  40. featureStore.addFeatures(collection);
  41. transaction.commit();
  42. } catch (Exception problem) {
  43. problem.printStackTrace();
  44. transaction.rollback();
  45. } finally {
  46. transaction.close();
  47. }
  48. } else {
  49. System.out.println(typeName + " does not support read/write access");
  50. }
  51. } catch (Exception e) {
  52. e.printStackTrace();
  53. }
  54. }

以下代码对应geotools10.0版本

一、读shp文件(图形信息+属性信息)的写法:

  1. import java.io.File;
  2. import java.nio.charset.Charset;
  3. import java.util.Iterator;
  4. import org.geotools.data.shapefile.ShapefileDataStore;
  5. import org.geotools.data.shapefile.ShapefileDataStoreFactory;
  6. import org.geotools.data.simple.SimpleFeatureIterator;
  7. import org.geotools.data.simple.SimpleFeatureSource;
  8. import org.opengis.feature.Property;
  9. import org.opengis.feature.simple.SimpleFeature;
  10. public class ShpNew {
  11. public static void main(String[] args) {
  12. ShapefileDataStoreFactory dataStoreFactory = new ShapefileDataStoreFactory();
  13. try {
  14. ShapefileDataStore sds = (ShapefileDataStore)dataStoreFactory.createDataStore(new File("D:\\work\\shpdir\\Poi.shp").toURI().toURL());
  15. sds.setCharset(Charset.forName("GBK"));
  16. SimpleFeatureSource featureSource = sds.getFeatureSource();
  17. SimpleFeatureIterator itertor = featureSource.getFeatures().features();
  18. while(itertor.hasNext()) {
  19. SimpleFeature feature = itertor.next();
  20. Iterator<Property> it = feature.getProperties().iterator();
  21. while(it.hasNext()) {
  22. Property pro = it.next();
  23. System.out.println(pro);
  24. }
  25. }
  26. itertor.close();
  27. } catch (Exception e) {
  28. e.printStackTrace();
  29. }
  30. }
  31. }

二、读图形信息

  1. try {
  2. ShpFiles sf = new ShpFiles("D:\\Poi.shp");
  3. ShapefileReader r = new ShapefileReader( sf, false, false, new GeometryFactory() );
  4. while (r.hasNext()) {
  5. Geometry shape = (Geometry) r.nextRecord().shape();  //com.vividsolutions.jts.geom.Geometry;
  6. System.out.println(shape.toString());
  7. }
  8. r.close();
  9. } catch (Exception e) {
  10. e.printStackTrace();
  11. }

三、读dbf文件

  1. public void readDBF() {
  2. try {
  3. FileChannel in = new FileInputStream("D:\\Poi.dbf").getChannel();
  4. DbaseFileReader dbfReader =  new DbaseFileReader(in, false,  Charset.forName("GBK"));
  5. DbaseFileHeader header = dbfReader.getHeader();
  6. int fields = header.getNumFields();
  7. while ( dbfReader.hasNext() ){
  8. DbaseFileReader.Row row =  dbfReader.readRow();
  9. //              System.out.println(row.toString());
  10. for (int i=0; i<fields; i++) {
  11. System.out.println(header.getFieldName(i) + " : " + row.read(i));
  12. }
  13. }
  14. dbfReader.close();
  15. in.close();
  16. } catch (Exception e) {
  17. e.printStackTrace();
  18. }
  19. }

四、写shape文件

  1. public void write(String filepath) {
  2. try {
  3. //创建shape文件对象
  4. File file = new File(filepath);
  5. Map<String, Serializable> params = new HashMap<String, Serializable>();
  6. params.put( ShapefileDataStoreFactory.URLP.key, file.toURI().toURL() );
  7. ShapefileDataStore ds = (ShapefileDataStore) new ShapefileDataStoreFactory().createNewDataStore(params);
  8. //定义图形信息和属性信息
  9. SimpleFeatureTypeBuilder tb = new SimpleFeatureTypeBuilder();
  10. tb.setCRS(DefaultGeographicCRS.WGS84);
  11. tb.setName("shapefile");
  12. tb.add("the_geom", Point.class);
  13. tb.add("POIID", Long.class);
  14. tb.add("NAMEC", String.class);
  15. ds.createSchema(tb.buildFeatureType());
  16. ds.setCharset(Charset.forName("GBK"));
  17. //设置Writer
  18. FeatureWriter<SimpleFeatureType, SimpleFeature> writer = ds.getFeatureWriter(ds.getTypeNames()[0], Transaction.AUTO_COMMIT);
  19. //写下一条
  20. SimpleFeature feature = writer.next();
  21. feature.setAttribute("the_geom", new GeometryFactory().createPoint(new Coordinate(116.123, 39.345)));
  22. feature.setAttribute("POIID", 1234567890l);
  23. feature.setAttribute("NAMEC", "某兴趣点1");
  24. feature = writer.next();
  25. feature.setAttribute("the_geom", new GeometryFactory().createPoint(new Coordinate(116.456, 39.678)));
  26. feature.setAttribute("POIID", 1234567891l);
  27. feature.setAttribute("NAMEC", "某兴趣点2");
  28. writer.write();
  29. writer.close();
  30. ds.dispose();
  31. //读取刚写完shape文件的图形信息
  32. ShpFiles shpFiles = new ShpFiles(filepath);
  33. ShapefileReader reader = new ShapefileReader(shpFiles, false, true, new GeometryFactory(), false);
  34. try {
  35. while (reader.hasNext()) {
  36. System.out.println(reader.nextRecord().shape());
  37. }
  38. } finally {
  39. reader.close();
  40. }
  41. } catch (Exception e) { }
  42. }

五、由源shape文件创建新的shape文件

  1. public void transShape(String srcfilepath, String destfilepath) {
  2. try {
  3. //源shape文件
  4. ShapefileDataStore shapeDS = (ShapefileDataStore) new ShapefileDataStoreFactory().createDataStore(new File(srcfilepath).toURI().toURL());
  5. //创建目标shape文件对象
  6. Map<String, Serializable> params = new HashMap<String, Serializable>();
  7. FileDataStoreFactorySpi factory = new ShapefileDataStoreFactory();
  8. params.put(ShapefileDataStoreFactory.URLP.key, new File(destfilepath).toURI().toURL());
  9. ShapefileDataStore ds = (ShapefileDataStore) factory.createNewDataStore(params);
  10. // 设置属性
  11. SimpleFeatureSource fs = shapeDS.getFeatureSource(shapeDS.getTypeNames()[0]);
  12. //下面这行还有其他写法,根据源shape文件的simpleFeatureType可以不用retype,而直接用fs.getSchema设置
  13. ds.createSchema(SimpleFeatureTypeBuilder.retype(fs.getSchema(), DefaultGeographicCRS.WGS84));
  14. //设置writer
  15. FeatureWriter<SimpleFeatureType, SimpleFeature> writer = ds.getFeatureWriter(ds.getTypeNames()[0], Transaction.AUTO_COMMIT);
  16. //写记录
  17. SimpleFeatureIterator it = fs.getFeatures().features();
  18. try {
  19. while (it.hasNext()) {
  20. SimpleFeature f = it.next();
  21. SimpleFeature fNew = writer.next();
  22. fNew.setAttributes(f.getAttributes());
  23. writer.write();
  24. }
  25. } finally {
  26. it.close();
  27. }
  28. writer.close();
  29. ds.dispose();
  30. shapeDS.dispose();
  31. } catch (Exception e) { e.printStackTrace();    }
  32. }

JAVA用geotools读写shape格式文件的更多相关文章

  1. JAVA用geotools读取shape格式文件

    Shapefile属于一种矢量图形格式,它能够保存几何图形的位置及相关属性.但这种格式没法存储地理数据的拓扑信息. 其中,要组成一个Shapefile,有三个文件是必不可少的,它们分别是". ...

  2. 使用Spark读写CSV格式文件(转)

    原文链接:使用Spark读写CSV格式文件 CSV格式的文件也称为逗号分隔值(Comma-Separated Values,CSV,有时也称为字符分隔值,因为分隔字符也可以不是逗号.在本文中的CSV格 ...

  3. Java使用Geotools读取shape矢量数据

    作为GIS开发者而言,矢量数据是我们经常要用到的,而shape数据是矢量数据中最常用的格式,因此解析shape数据也是作为GIS软件开发人员必备的基础技能,而GeoTools无疑是Java最好用来处理 ...

  4. java 调用OpenOffice将word格式文件转换为pdf格式

    一:环境搭建 OpenOffice 下载地址http://www.openoffice.org/ JodConverter 下载地址http://sourceforge.net/projects/jo ...

  5. 如何用python读写CSV 格式文件

    工作中经常会碰到读写CSV文件的情况.记录下,方便自己以后查询并与大家一起分享: 写CSV文件方法一: import csv          #导入CSV with open("D:\eg ...

  6. python利用lxml读写xml格式文件

    之前在转换数据集格式的时候需要将json转换到xml文件,用lxml包进行操作非常方便. 1. 写xml文件 a) 用etree和objectify from lxml import etree, o ...

  7. java使用jdom生成xml格式文件

    本文生成xml使用的工具是jdom.jar,下载地址如下: 链接:https://eyun.baidu.com/s/3slyHgnj 密码:0TXF 生成之后的文档格式类型,就如上面的图片一样,简单吧 ...

  8. 使用csv模块读写csv格式文件

    import csv class HandleCsv: ''' csv文件处理类 ''' def __init__(self, filename): ''' 构造器 :param filename: ...

  9. 使用JAVA读写Properties属性文件

     使用JAVA读写Properties属性文件 Properties属性文件在JAVA应用程序中是经常可以看得见的,也是特别重要的一类文件.它用来配置应用程序的一些信息,不过这些信息一般都是比较少的数 ...

随机推荐

  1. MAC itunes无法验证服务器s.mzstatic/itunes无法更新服务器解决方案

    打开host文件: 一.用终端打开: sudo vi /etc/hosts 输入完这行命令后需要输入电脑密码,然后确认,进入host文件 然后按i键进入编辑模式,在最后一行添加:23.214.233. ...

  2. UiTextField对输入的长度进行限制并提示用户还可输入的长度

    最近想做用户昵称的限制,但是网上百度了很多方法效果都不是我自己想要的,终于找到种方法 如下: 1.声明两个属性 nickname是昵称的textfleld canEditSizeLAbel是提示用户剩 ...

  3. WPF动画之线性插值动画(1)

    XAML代码: <Window x:Class="线性插值动画.MainWindow" xmlns="http://schemas.microsoft.com/wi ...

  4. windows server 2003 禁止开机显示“关闭事件跟踪”

    关机事件跟踪(Shutdown   Event   Tracker)也是Windows   server   2003区别于其他工作站系统的一个设置,对于服务器来说这是一个必要的选择,但是对于工作站系 ...

  5. UVA 11078 Open Credit System(扫描 维护最大值)

    Open Credit System In an open credit system, the students can choose any course they like, but there ...

  6. 什么是CGI(Common Gateway Interface)?

    参考: 1.Python CGI编程 2.十分钟搞懂CGI 3.CGI Made Really Easy

  7. 使用GitHub For Windows托管Visual Studio项目

    本文写得比较早,更新的在VS上使用GitHub的文章请移步:Visual Stuido 2015 Community 使用 GitHub 插件 因为最近同时再看很多技术方面的书,书上的例子有很多自己想 ...

  8. Android版多线程下载器核心代码分享

    首先给大家分享多线程下载核心类: package com.example.urltest; import java.io.IOException; import java.io.InputStream ...

  9. 【POJ2094】【差分序列】Angry Teacher

    Description Mr. O'Cruel is teaching Math to ninth grade students. Students of course are very lazy, ...

  10. 锋利的Jquery解惑系列(一)------基本概念大锅炖

    声明:虽然是基本概念但也是笔者经过一番学习才总结的这些文章,所以他不包括Jquery优缺点.特点.语法的介绍. 概念一:jQuery对像与DOM对象 DOM(Document Object Model ...