`
toplchx
  • 浏览: 341977 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

JAVA用geotools读写shape格式文件

    博客分类:
  • geo
阅读更多

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();	}
	}
 

 

分享到:
评论
8 楼 zhang90030 2018-02-23  
location:Point 应该为 the_geom:Point,不然空间坐标写入不进去
7 楼 hanbuhe 2017-02-07  
Property 是用的哪个包的呀?我这里get方法用不了
6 楼 hanbuhe 2017-02-07  
楼主  我正在用你这个例子呢,2.7的jar包能贴出来吗?
import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.nio.charset.Charset;
import java.util.Collection;
import java.util.Iterator;

import org.geotools.data.FeatureSource;
import org.geotools.data.shapefile.ShapefileDataStore;
import org.geotools.data.shapefile.ShpFiles;
import org.geotools.data.shapefile.dbf.DbaseFileHeader;
import org.geotools.data.shapefile.dbf.DbaseFileReader;
import org.geotools.feature.FeatureCollection;
import org.geotools.feature.FeatureIterator;
import org.geotools.feature.SimpleFeature;
import org.geotools.feature.SimpleFeatureType;
import org.opengis.feature.Property;
import org.opengis.geometry.primitive.Point;
这是我的
5 楼 PCstudy 2015-04-13  
你好,楼主,我想用geotools工具取postgis之中的gid属性,该怎么取?gid是postgis里面的主键。
4 楼 zhan8863 2014-09-01  
      谢谢分享,最近正需要这类东西做参考!!!   
3 楼 toplchx 2014-07-21  
ljk83875 写道
用了哪些jar能说下不  761626336

2.7版就不说了。
10.0版本读shp和dbf的包可以参考这些:(不是全必要)
import java.io.File;
import java.io.FileInputStream;
import java.nio.channels.FileChannel;
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.shapefile.dbf.DbaseFileHeader;
import org.geotools.data.shapefile.dbf.DbaseFileReader;
import org.geotools.data.shapefile.files.ShpFiles;
import org.geotools.data.shapefile.shp.ShapefileReader;
import org.geotools.data.simple.SimpleFeatureIterator;
import org.geotools.data.simple.SimpleFeatureSource;
import org.opengis.feature.Property;
import org.opengis.feature.simple.SimpleFeature;

import com.vividsolutions.jts.geom.Geometry;
import com.vividsolutions.jts.geom.GeometryFactory;

写shape的包参考:
import java.io.File;
import java.io.Serializable;
import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.Map;

import org.geotools.data.FeatureWriter;
import org.geotools.data.FileDataStoreFactorySpi;
import org.geotools.data.Transaction;
import org.geotools.data.shapefile.ShapefileDataStore;
import org.geotools.data.shapefile.ShapefileDataStoreFactory;
import org.geotools.data.shapefile.files.ShpFiles;
import org.geotools.data.shapefile.shp.ShapefileReader;
import org.geotools.data.simple.SimpleFeatureIterator;
import org.geotools.data.simple.SimpleFeatureSource;
import org.geotools.feature.simple.SimpleFeatureTypeBuilder;
import org.geotools.referencing.crs.DefaultGeographicCRS;
import org.opengis.feature.simple.SimpleFeature;
import org.opengis.feature.simple.SimpleFeatureType;

import com.vividsolutions.jts.geom.Coordinate;
import com.vividsolutions.jts.geom.GeometryFactory;
import com.vividsolutions.jts.geom.Point;
2 楼 ljk83875 2014-07-18  
用了哪些jar能说下不  761626336
1 楼 睡神Mark 2012-10-31  
赞一个,好东西啊

相关推荐

    geotools读取*dbf/*shp文件

    标题 "geotools读取*.dbf/*.shp文件" 涉及的是使用开源Java库GeoTools处理地理空间数据的技巧。GeoTools是一个用于处理地理信息系统(GIS)数据的库,它支持多种地理空间数据格式,包括Shapefile(*.shp)和DBF(*....

    GeoTools Demo的shape格式文件,50m_cultural.zip

    在这个“GeoTools Demo”的示例中,我们重点关注的是如何利用GeoTools来读取shape格式(.shp)的地理数据文件。Shapefile是一种常见的地理空间数据存储格式,它由多个相关的文件组成,包括.shp主文件,以及.dbf...

    javafx+geotools实现shape读写工具

    JavaFX和GeoTools结合可以创建一个强大的地理信息系统(GIS)应用程序,主要针对shape文件的读写操作。在本文中,我们将深入探讨如何利用这两个技术来实现所述的功能。 首先,JavaFX是一个用于创建桌面和移动应用的...

    geotools对wms的实现支持

    GeoTools 是一个基于 Java 语言的开源 GIS 工具包,提供了地理信息数据读写、处理、坐标转换、查询分析、格式化输出等多个方面的功能。GeoTools 的主要功能包括: * 地理信息数据读写:GeoTools 提供了对多种地理...

    Geotools Java API 开发gis的参考资料

    org.geotools.renderer.shape.shapehandler.simple org.geotools.renderer.style org.geotools.repository org.geotools.repository.adaptable org.geotools.repository.defaults org.geotools.repository....

    等值线等值面功能实现.使用技术包括Java+Geotools+WContour+Openlayers

    在这个项目中,开发者利用了Java编程语言、Geotools库、WContour模块以及OpenLayers框架来完成这一功能。下面我们将详细探讨这些技术在等值线等值面生成过程中的作用。 1. **Java**: Java是一种广泛使用的面向对象...

    Java+Geotools+WContour+Openlayers实现等值线等值面功能

    1. 数据预处理:使用Java读取和解析地理空间数据,例如,你可以加载一个GeoTIFF文件,将其转化为Geotools支持的GridCoverage2D对象。 2. 等值线生成:利用Geotools的WContour模块,根据数据的特性设置合适的等值...

    Java1.8使用GeoTools28.x实现shapefile转图片实战源码

    这是一份使用Java开发的,jdk的版本是1.8,GeoTools28版本的Shapefile文件向图片文件生成的源代码,在源码中包含了全球的矢量数据。文件是在geotools-fx的一个项目上进行二次扩展的,保留了原始的矢量数据。代码保留...

    GeoTools是一个开源的Java库提供地理空间数据工具

    GeoTools是专为Java开发者设计的一个强大的开源库,它提供了丰富的功能来处理地理空间数据,使得在Java应用程序中集成和操作地图、空间坐标系统、地理编码等地理信息变得轻松便捷。这个库支持多种开放标准,如OGC...

    Java解析shpfile所需要的geotools包

    Java解析SHP文件是地理信息系统(GIS)领域中的常见任务,而Geotools是一个开源的Java库,专门用于处理各种地理空间数据,包括ESRI的Shapefile格式。在这个场景下,"Java解析shpfile所需要的geotools包"指的是利用...

    geotools汉语版资料

    《GeoTools汉语版资料》是一份详实的资源集合,主要针对使用GeoTools进行地理信息系统(GIS)开发的用户。GeoTools是一个开放源代码的Java库,它实现了OGC(Open Geospatial Consortium)标准,提供了对地理空间数据...

    geotools稳定版本geotools-19.4-bin.zip

    import org.geotools.data.FileDataStore; import org.geotools.data.FileDataStoreFinder; import org.geotools.data.simple.SimpleFeatureSource; import org.geotools.map.FeatureLayer; import org.geotools.map...

    geotools依赖包

    GeoTools是一个开源的Java库,专门用于处理地理空间数据。这个“geotools依赖包”包含了一组模块,用于支持各种地理信息系统(GIS)的功能,如读取、写入和操作地理空间数据。GeoTools库遵循Java Community Process ...

    geoTools所需jar包

    GeoTools是一个开源的Java库,专门用于处理地理空间数据和执行与GIS(地理信息系统)相关的操作。这个"geoTools所需jar包"包含了经过编译和打包的GeoTools库,使得开发者可以直接在他们的项目中使用,而无需经历繁琐...

    SpringBoot项目中使用GeoTools解析.shp文件

    在SpringBoot项目中使用GeoTools解析.shp文件,代码在测试类中。

    geotools依赖.rar

    《GeoTools源码构建的关键依赖...理解并掌握这些依赖的作用,对于成功构建和使用GeoTools源码至关重要。通过分享这些依赖包,开发者们可以在任何网络环境下便捷地进行GeoTools项目的工作,推动GIS应用的开发和创新。

    geotools所需jar包合集

    1. **Java**:表明GeoTools是基于Java语言的,适合Java开发者使用。 2. **geotools**:这是库的名字,强调了这是关于GeoTools的内容。 3. **sha转geojson**:SHA可能是指文件的哈希值,而GeoJSON是一种轻量级的数据...

    geotools.rar

    标题中的"geotools.rar"可能是一个包含不同版本Geotools库的压缩文件,其中特别提到了14.1和24版本。这两个版本代表了Geotools的发展历程,24版本尤其引人注目,因为它增加了对坐标转换的强大支持。 坐标转换是GIS...

Global site tag (gtag.js) - Google Analytics