读取 shapefile 文件
package com.meic.test;
import java.io.File;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;
import org.geotools.data.FeatureSource;
import org.geotools.data.shapefile.ShapefileDataStore;
import org.geotools.data.shapefile.files.ShpFiles;
import org.geotools.data.shapefile.shp.ShapefileReader;
import org.geotools.feature.FeatureCollection;
import org.geotools.feature.FeatureIterator;
import org.opengis.feature.simple.SimpleFeature;
import org.opengis.feature.simple.SimpleFeatureType;
import com.vividsolutions.jts.geom.Geometry;
import com.vividsolutions.jts.geom.GeometryFactory;
/**
* 使用GeoTools读取shapefile示例
*
* @author alei
*
*/
public class ReadShpExample {
/**
* 使用ShapefileReader读取
*
* @param file
* shapefile
* @return 几何形状列表
* @throws Exception
*/
public List<Geometry> read1(String file) throws Exception {
List<Geometry> _geometrys = new ArrayList<>();
ShpFiles sf = new ShpFiles(file);
ShapefileReader r = new ShapefileReader(sf, false, false, new GeometryFactory());
while (r.hasNext()) {
Geometry _shape = (Geometry) r.nextRecord().shape();
_geometrys.add(_shape);
}
r.close();
return _geometrys;
}
/**
* 使用ShapefileDataStore读取
*
* @param file
* shapefile
* @return 几何形状列表
* @throws Exception
*/
public List<Geometry> read2(String file) throws Exception {
List<Geometry> _geometrys = new ArrayList<>();
ShapefileDataStore _shpDataStore = new ShapefileDataStore(new File(file).toURI().toURL());
_shpDataStore.setCharset(Charset.forName("latin1"));
String _typeName = _shpDataStore.getTypeNames()[0];
FeatureSource<SimpleFeatureType, SimpleFeature> _featureSource = (FeatureSource<SimpleFeatureType, SimpleFeature>) _shpDataStore.getFeatureSource(_typeName);
FeatureCollection<SimpleFeatureType, SimpleFeature> _collection = _featureSource.getFeatures();
FeatureIterator<SimpleFeature> _itertor = _collection.features();
while (_itertor.hasNext()) {
SimpleFeature _feature = _itertor.next();
Geometry _geometry = (Geometry) _feature.getDefaultGeometry();
_geometrys.add(_geometry);
}
_itertor.close();
return _geometrys;
}
}