• JAVA用geotools读写shape格式文件
    时间:2014-08-04   作者:佚名   出处:互联网

    JAVA用geotools读写shape格式文件的几个例子

    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();
            }
        }
    }
    /**
     * 读图形信息
     */
    public function void readFile(){
        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();
        }
    }

    网友留言/评论

    我要留言/评论

    相关文章

    JTS(Geometry) 简单例子:本文主要介绍使用JTS进行几何图形的基本操作。
    GeoTools是什么,以及与JTS和GeoAPI之间的关系如何?:Geotools是一个java类库,它提供了很多的标准类和方法来处理空间数据,同时这个类库是构建在OGC标准之上的,是OGC思想的一种实现。而OGC是国际标准,所以geotools将来必定会成为开源空间数据处理的主要工具,目前的大部分开源软件,如udig,geoserver等,对空间数据的处理都是由geotools来做支撑。而其他很多的web服务,命令行工具和桌面程序都可以由geotools来实现。
    程序那些事:日志记录的作用和方法:程序中记录日志一般有两个目的:Troubleshooting和显示程序运行状态。好的日志记录方式可以提供我们足够多定位问题的依据。日志记录大家都会认为简单,但如何通过日志可以高效定位问题并不是简单的事情。这里列举下面三个方面的内容,辅以代码示例,总结如何写好日志,希望对他人有所启发和帮助:1、怎样记日志可以方便Troubleshooting。 2、程序运行状态可以记哪些。3、应该避免怎样的日志方式。
    Lucene 基础理论与实例:Lucene是apache软件基金会4 jakarta项目组的一个子项目,是一个开放源代码的全文检索引擎工具包,即它不是一个完整的全文检索引擎,而是一个全文检索引擎的架构,提供了完整的查询引擎和索引引擎,部分文本分析引擎(英文与德文两种西方语言)。Lucene的目的是为软件开发人员提供一个简单易用的工具包,以方便的在目标系统中实现全文检索的功能,或者是以此为基础建立起完整的全文检索引擎。本文将介绍Lucene 基础理论与实例。
    List,set,Map 的用法和区别等:List按对象进入的顺序保存对象,不做排序或编辑操作。Set对每个对象只接受一次,并使用自己内部的排序方法(通常,你只关心某个元素是否属于Set,而不关心它的顺序--否则应该使用List)。Map同样对每个元素保存一份,但这是基于"键"的,Map也有内置的排序,因而不关心元素添加的顺序。如果添加元素的顺序对你很重要,应该使用 LinkedHashSet或者LinkedHashMap.
    web压力测试工具集介绍:当一套程序写完或者一台服务器配置完成后,相必很多朋友会像我一样,非 常想知道它到底能 够承受多大的负载压力,那在本文中,就给大家介绍十个免 费的可以用来进行 Web 的负载/压力测试的工具,这样,你就可以知道你的服务 器以及你的 Web 应用 能够顶得住多少的并发量,以及你的网站的性能。
    五种 JSP页面跳转方法详解:本文向您介绍Servlet页面跳转实现方法的几种区别,包括Servlet和JSP中的不同实现,比如Servlet中的redirect方式和forward方式得区别等。
    JAVA,HashSet面试题:本文列举java面试题中关于HashSet的一些知识点
    开源混淆工具ProGuard配置详解及配置实例:ProGuard是一个免费的java类文件压缩,优化,混淆器.它探测并删除没有使用的类,字段,方法和属性.它删除没有用的说明并使用字节码得到最大优化.它使用无意义的名字来重命名类,字段和方法.
    在代码重构中蜕变:这几天,要对我半年前写的代码进行一些整理工作,在看代码时发现当时有很多地方写得不够好,俗称的有“坏味道”,呵呵,重构,必须的。