geotools系列1-读取shp文件

.shp文件是目前大家使用频率较高而且通用的一种格式。此篇主要说明geotools对shp文件的读取说明。

 

1、maven依赖,包含了postgis支持、epsg、和swing的支持,后续的文章基本都基于此

 


  4.0.0

  com.jjxliu.geotools
  geotools_t1
  0.0.1-SNAPSHOT
  jar

  geotools_t1
  http://maven.apache.org

  
    UTF-8
     20-SNAPSHOT
  

        
            junit
            junit
            4.11
            test
        
        
            org.geotools
            gt-shapefile
            ${geotools.version}
        
        
            org.geotools
            gt-swing
            ${geotools.version}
        
        
  			org.geotools
  			gt-jdbc
  			${geotools.version}
		
        
   			org.geotools.jdbc
   			gt-jdbc-postgis
   			${geotools.version}
 		
 	
 		
   			org.geotools
   			gt-epsg-hsql
   			${geotools.version}
 		
 		
    
     
        
            maven2-repository.dev.java.net
            Java.net repository
            http://download.java.net/maven/2
        
        
            osgeo
            Open Source Geospatial Foundation Repository
            http://download.osgeo.org/webdav/geotools/
        
        
          
            true
          
          boundless
          Boundless Maven Repository
          http://repo.boundlessgeo.com/main
        
    
     
        
            
                true
                org.apache.maven.plugins
                maven-compiler-plugin
                
                    1.8
                    1.8
                
            
        
    

 

 

2、直接上java代码说明shp文件读取

public static SimpleFeatureCollection  readShp(String path ){
		return readShp(path, null);
		
	}

	public static SimpleFeatureCollection  readShp(String path , Filter filter){
	  
		SimpleFeatureSource  featureSource = readStoreByShp(path);
		   
		if(featureSource == null) return null;
          
		try {
			return filter != null ? featureSource.getFeatures(filter) : featureSource.getFeatures() ;
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} 
         
         return null ;
	}
	
	public static  SimpleFeatureSource readStoreByShp(String path ){
		 
		File file = new File(path);
    	 
		FileDataStore store;
		SimpleFeatureSource featureSource = null;
		try {
			store = FileDataStoreFinder.getDataStore(file);
			 ((ShapefileDataStore) store).setCharset(Charset.forName("UTF-8"));
			featureSource = store.getFeatureSource();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
         
         return featureSource ;
	}

 

3、测试一段读取的代码,打印所有读取到的simplefeature

String path1 = "G:/work/china_map/shp/BOUNT_poly.shp" ;
		
		//读取shp
		SimpleFeatureCollection  colls1 = readShp(path1);
		//拿到所有features
		SimpleFeatureIterator iters = colls1.features();
		//遍历打印
		while(iters.hasNext()){
			SimpleFeature sf = iters.next();
			
			System.out.println(sf.getID() + " , " + sf.getAttributes());
			
		}

 

打印贴图


geotools系列1-读取shp文件_第1张图片
 

 

实例的.java在附件。

 

 

 

你可能感兴趣的:(GIS)