首页 > 代码库 > JAVA用geotools读写shape格式文件

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) {

Java代码  收藏代码
  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) {

Java代码  收藏代码
  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为例:

 

Java代码  收藏代码
  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.   
  14.         double latitude = Double.parseDouble("116.123456789");  
  15.         double longitude = Double.parseDouble("39.120001");  
  16.         String POIID = "2050003092";  
  17.         String MESHID = "0";  
  18.         String OWNER = "340881";  
  19.   
  20.         /* Longitude (= x coord) first ! */  
  21.         Point point = geometryFactory.createPoint(new Coordinate(longitude, latitude));  
  22.         Object[] obj = {point, POIID, MESHID, OWNER};  
  23.         SimpleFeature feature = featureBuilder.buildFeature(null, obj);  
  24.         collection.add(feature);  
  25.         feature = featureBuilder.buildFeature(null, obj);  
  26.         collection.add(feature);  
  27.   
  28.         File newFile = new File("D:/newPoi.shp");  
  29.         ShapefileDataStoreFactory dataStoreFactory = new ShapefileDataStoreFactory();  
  30.         Map<String, Serializable> params = new HashMap<String, Serializable>();  
  31.         params.put("url", newFile.toURI().toURL());  
  32.         params.put("create spatial index", Boolean.TRUE);  
  33.         ShapefileDataStore newDataStore = (ShapefileDataStore) dataStoreFactory.createNewDataStore(params);  
  34.         newDataStore.createSchema(TYPE);  
  35.         newDataStore.forceSchemaCRS(DefaultGeographicCRS.WGS84);  
  36.   
  37.         Transaction transaction = new DefaultTransaction("create");  
  38.         String typeName = newDataStore.getTypeNames()[0];  
  39.         SimpleFeatureSource featureSource = newDataStore.getFeatureSource(typeName);  
  40.   
  41.         if (featureSource instanceof SimpleFeatureStore) {  
  42.             SimpleFeatureStore featureStore = (SimpleFeatureStore) featureSource;  
  43.             featureStore.setTransaction(transaction);  
  44.             try {  
  45.                 featureStore.addFeatures(collection);  
  46.                 transaction.commit();  
  47.             } catch (Exception problem) {  
  48.                 problem.printStackTrace();  
  49.             transaction.rollback();  
  50.             } finally {  
  51.                 transaction.close();  
  52.             }  
  53.         } else {  
  54.             System.out.println(typeName + " does not support read/write access");  
  55.         }  
  56.     } catch (Exception e) {  
  57.         e.printStackTrace();  
  58.     }  
  59. }  

 

 以下代码对应geotools10.0版本

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

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

 

 二、读图形信息

Java代码  收藏代码
  1. try {  
  2.     ShpFiles sf = new ShpFiles("D:\\Poi.shp");  
  3.     ShapefileReader r = new ShapefileReader( sf, falsefalsenew 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文件

Java代码  收藏代码
  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.               
  8.             while ( dbfReader.hasNext() ){  
  9.                 DbaseFileReader.Row row =  dbfReader.readRow();  
  10. //              System.out.println(row.toString());  
  11.                 for (int i=0; i<fields; i++) {  
  12.                     System.out.println(header.getFieldName(i) + " : " + row.read(i));     
  13.                 }  
  14.             }  
  15.             dbfReader.close();  
  16.             in.close();  
  17.         } catch (Exception e) {  
  18.             e.printStackTrace();  
  19.         }  
  20.     }  

 

四、写shape文件

Java代码  收藏代码
  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.12339.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.45639.678)));  
  26.         feature.setAttribute("POIID", 1234567891l);  
  27.         feature.setAttribute("NAMEC""某兴趣点2");  
  28.         writer.write();  
  29.         writer.close();  
  30.         ds.dispose();  
  31.           
  32.         //读取刚写完shape文件的图形信息  
  33.         ShpFiles shpFiles = new ShpFiles(filepath);  
  34.         ShapefileReader reader = new ShapefileReader(shpFiles, falsetruenew GeometryFactory(), false);  
  35.         try {  
  36.             while (reader.hasNext()) {  
  37.                 System.out.println(reader.nextRecord().shape());      
  38.             }  
  39.         } finally {  
  40.             reader.close();  
  41.         }  
  42.     } catch (Exception e) { }  
  43. }  

 

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

 

Java代码  收藏代码
  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.           
  15.         //设置writer  
  16.         FeatureWriter<SimpleFeatureType, SimpleFeature> writer = ds.getFeatureWriter(ds.getTypeNames()[0], Transaction.AUTO_COMMIT);  
  17.           
  18.         //写记录  
  19.         SimpleFeatureIterator it = fs.getFeatures().features();  
  20.         try {  
  21.             while (it.hasNext()) {  
  22.                 SimpleFeature f = it.next();  
  23.                 SimpleFeature fNew = writer.next();  
  24.                 fNew.setAttributes(f.getAttributes());  
  25.                 writer.write();  
  26.             }  
  27.         } finally {  
  28.             it.close();  
  29.         }  
  30.         writer.close();  
  31.         ds.dispose();  
  32.         shapeDS.dispose();  
  33.     } catch (Exception e) { e.printStackTrace();    }  
  34. }