<dependency>
<groupId>org.geotools</groupId>
<artifactId>gt-shapefile</artifactId>
<version>19.1</version>
</dependency>
<dependency>
<groupId>org.geotools</groupId>
<artifactId>gt-swing</artifactId>
<version>19.1</version>
</dependency>
<dependency>
<groupId>org.geotools</groupId>
<artifactId>gt-jdbc</artifactId>
<version>19.1</version>
</dependency>
<dependency>
<groupId>org.geotools.jdbc</groupId>
<artifactId>gt-jdbc-postgis</artifactId>
<version>19.1</version>
</dependency>
<dependency>
<groupId>org.geotools</groupId>
<artifactId>gt-epsg-hsql</artifactId>
<version>19.1</version>
</dependency>
创建工具类
import org.geotools.data.FileDataStore;
import org.geotools.data.FileDataStoreFinder;
import org.geotools.data.shapefile.ShapefileDataStore;
import org.geotools.data.simple.SimpleFeatureCollection;
import org.geotools.data.simple.SimpleFeatureIterator;
import org.geotools.data.simple.SimpleFeatureSource;
import org.opengis.feature.simple.SimpleFeature;
import org.opengis.filter.Filter;
import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;
/*
* 读取本地shp文件
* */
public class ReadShepUtil {
public static void main(String[] args){
String path1 = "F:\\test\\test.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());
}
}
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) {
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("GBK"));
featureSource = store.getFeatureSource();
} catch (IOException e) {
e.printStackTrace();
}
return featureSource ;
}
}