直接上代码
import org.geotools.data.*;
import org.geotools.data.collection.ListFeatureCollection;
import org.geotools.data.shapefile.ShapefileDataStore;
import org.geotools.data.shapefile.ShapefileDataStoreFactory;
import org.geotools.data.simple.SimpleFeatureCollection;
import org.geotools.data.simple.SimpleFeatureSource;
import org.geotools.data.simple.SimpleFeatureStore;
import org.geotools.feature.FeatureCollection;
import org.geotools.feature.FeatureIterator;
import org.geotools.feature.simple.SimpleFeatureBuilder;
import org.geotools.geojson.GeoJSONUtil;
import org.geotools.geojson.feature.FeatureJSON;
import org.geotools.geojson.geom.GeometryJSON;
import org.geotools.referencing.CRS;
import org.locationtech.jts.geom.*;
import org.opengis.feature.simple.SimpleFeature;
import org.opengis.feature.simple.SimpleFeatureType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.*;
public class RwUtils {
private static Logger logger = LoggerFactory.getLogger(RwUtils.class);
public static List<? extends Geometry> toSimple(List<? extends Geometry> geometryList) {
List< Geometry> simpleLineList = new ArrayList<>();
for (Geometry geometry : geometryList) {
if (geometry instanceof MultiLineString || geometry instanceof MultiPolygon || geometry instanceof MultiPoint) {
for (int j = 0; j < geometry.getNumGeometries(); j += 1) {
simpleLineList.add(geometry.getGeometryN(j));
}
} else if (geometry instanceof LineString || geometry instanceof Polygon || geometry instanceof Point) {
simpleLineList.add(geometry);
}
}
return simpleLineList;
}
public static List<SimpleFeature> toSimpleFeature(List<SimpleFeature> simpleFeatureList){
List<SimpleFeature> resultList = new ArrayList<>();
for (SimpleFeature simpleFeature: simpleFeatureList) {
Geometry geometry = (Geometry) simpleFeature.getDefaultGeometry();
if (geometry instanceof MultiLineString || geometry instanceof MultiPolygon || geometry instanceof MultiPoint) {
for (int i = 0; i < geometry.getNumGeometries(); i += 1) {
SimpleFeature clone = SimpleFeatureBuilder.deep(simpleFeature);
clone.setDefaultGeometry(geometry.getGeometryN(i));
resultList.add(clone);
}
} else if (geometry instanceof LineString || geometry instanceof Polygon || geometry instanceof Point) {
resultList.add(simpleFeature);
}
}
return resultList;
}
public static List<LineString> toSimpleLine(List<? extends Geometry> geometryList) {
List<LineString> simpleLineList = new ArrayList<>();
for (Geometry geometry : geometryList) {
if (geometry instanceof MultiLineString) {
for (int j = 0; j < geometry.getNumGeometries(); j += 1) {
simpleLineList.add((LineString) geometry.getGeometryN(j));
}
} else if (geometry instanceof LineString) {
simpleLineList.add((LineString) geometry);
}
}
return simpleLineList;
}
public static List<Geometry> readFeaturesShp(String path){
List<Geometry> geometryList = new ArrayList<>();
try {
File file = new File(path);
Map<String, Object> map = new HashMap<>();
map.put("url", file.toURI().toURL());
DataStore dataStore = DataStoreFinder.getDataStore(map);
String typeName = dataStore.getTypeNames()[0];
FeatureSource<SimpleFeatureType, SimpleFeature> source =
dataStore.getFeatureSource(typeName);
// Filter filter = Filter.INCLUDE; // ECQL.toFilter("BBOX(THE_GEOM, 10,20,30,40)")
geometryList = new ArrayList<>();
FeatureCollection<SimpleFeatureType, SimpleFeature> collection = source.getFeatures();
// features = collection.features();
// dataStore.dispose();
try (FeatureIterator<SimpleFeature> features = collection.features()) {
while (features.hasNext()) {
SimpleFeature feature = features.next();
Geometry geomrtry = (Geometry)feature.getDefaultGeometry();
geometryList.add(geomrtry);
}
features.close();
dataStore.dispose();
}
}catch (Exception e){
System.out.println(e);
}
return geometryList;
}
public static List<LineString> readCenterLineFeaturesShp(String path){
List<Geometry> geometryList = readFeaturesShp(path);
return toSimpleLine(geometryList);
}
public static List<Geometry> readGeoJson(String geojsonPath){
List<Geometry> geometryList = new ArrayList<>();
InputStreamReader reader = null;
try{
reader = new InputStreamReader(new FileInputStream(geojsonPath), "UTF-8");
FeatureIterator<SimpleFeature> features = new FeatureJSON().streamFeatureCollection(GeoJSONUtil.toReader(reader));
geometryList = new ArrayList<>();
while (features.hasNext()) {
SimpleFeature feature = features.next();
Geometry line = (Geometry) feature.getDefaultGeometry();
geometryList.add(line);
}
}catch (Exception e){
logger.error("=======================读取异常:" + e);
}finally {
try {
assert reader != null;
reader.close();
}catch (Exception e){
logger.error("=======================读取流关闭异常:" + e);
}
}
return geometryList;
}
public static List<LineString> readCenterLine(String path){
List<LineString> centerLineList = new ArrayList<>();
InputStreamReader reader = null;
try{
reader = new InputStreamReader(new FileInputStream(path), "UTF-8");
FeatureIterator<SimpleFeature> features = new FeatureJSON().streamFeatureCollection(GeoJSONUtil.toReader(reader));
List<Geometry> centerGeomList = new ArrayList<>();
while (features.hasNext()) {
SimpleFeature feature = features.next();
Geometry line = (Geometry) feature.getDefaultGeometry();
centerGeomList.add(line);
}
centerLineList = toSimpleLine(centerGeomList);
}catch (Exception e){
logger.error("=======================读取异常:" + e);
}finally {
try {
assert reader != null;
reader.close();
}catch (Exception e){
logger.error("=======================读取流关闭异常:" + e);
}
}
return centerLineList;
}
public static List<SimpleFeature> readCenterLineFeatures(String path){
List<SimpleFeature> featureList = new ArrayList<>();
InputStreamReader reader = null;
try{
reader = new InputStreamReader(new FileInputStream(path), "UTF-8");
FeatureIterator<SimpleFeature> features = new FeatureJSON().streamFeatureCollection(GeoJSONUtil.toReader(reader));
while (features.hasNext()) {
SimpleFeature feature = features.next();
featureList.add(feature);
}
}catch (Exception e){
logger.error("=======================读取异常:" + e);
}finally {
try {
assert reader != null;
reader.close();
}catch (Exception e){
logger.error("=======================读取流关闭异常:" + e);
}
}
return featureList;
}
public static void featureToShp(String path, List<SimpleFeature> outFeatures){
try {
FileDataStoreFactorySpi factory = new ShapefileDataStoreFactory();
File file = new File(path);
if (file.exists()) {
return;
}
Map map = Collections.singletonMap("url", file.toURI().toURL());
ShapefileDataStore dataStore = (ShapefileDataStore)factory.createNewDataStore(map);
SimpleFeatureType featureType =outFeatures.get(0).getType();
dataStore.createSchema(featureType);
dataStore.forceSchemaCRS(CRS.decode("EPSG:3857"));
/*
* Write the features to the shapefile
*/
Transaction transaction = new DefaultTransaction("create");
String typeName = dataStore.getTypeNames()[0];
SimpleFeatureSource featureSource = dataStore.getFeatureSource(typeName);
if (featureSource instanceof SimpleFeatureStore) {
SimpleFeatureStore featureStore = (SimpleFeatureStore) featureSource;
SimpleFeatureCollection collection = new ListFeatureCollection(featureType, outFeatures);
featureStore.setTransaction(transaction);
try {
featureStore.addFeatures(collection);
transaction.commit();
} catch (Exception problem) {
problem.printStackTrace();
transaction.rollback();
} finally {
transaction.close();
}
// System.exit(0); // success!
} else {
System.out.println(typeName + " does not support read/write access");
// System.exit(1);
}
}catch (Exception e){
System.out.println(e);
}
}
public static void featureToGeojson(String path, List<SimpleFeature> outFeatures){
Writer gjsonWriter = null;
try{
File file = new File(path);
if (file.exists()) {
file.delete();
}
if (outFeatures.isEmpty()) {
return;
}
FeatureJSON featureJSON = new FeatureJSON(new GeometryJSON(6));
// CoordinateReferenceSystem sourceCRS = CRS.decode("EPSG:3857");
gjsonWriter = new OutputStreamWriter(new FileOutputStream(singleRoadPath), StandardCharsets.UTF_8);
// featureJSON.writeCRS(sourceCRS,gjsonWriter);
featureJSON.writeFeatureCollection(new ListFeatureCollection(outFeatures.get(0).getType(), outFeatures), gjsonWriter);
}catch (Exception e){
logger.error("=======================feature写入异常:" + e);
}finally {
try{
if (gjsonWriter != null) {
gjsonWriter.flush();
gjsonWriter.close();
}
}catch (IOException ie){
logger.error("=======================流关闭异常:" + ie);
}
}
}
public static List<SimpleFeature> geometrysToGeojson( List<? extends Geometry> lineStringList, String lineType){
List<SimpleFeature> lineFeatures = new ArrayList<>();
try {
SimpleFeatureType type = DataUtilities.createType("line", lineType);
SimpleFeatureBuilder linefeatureBuilder = new SimpleFeatureBuilder(type);
linefeatureBuilder.add("id");
for (int i = 0; i < lineStringList.size(); i++) {
Geometry centerLine = lineStringList.get(i);
if(centerLine == null){
continue;
}
//linefeatureBuilder.set("id", String.valueOf(i));
SimpleFeature featureLine = linefeatureBuilder.buildFeature(String.valueOf(i));
featureLine.setDefaultGeometry(centerLine);
featureLine.setAttribute("id",String.valueOf(i));
lineFeatures.add(featureLine);
}
}catch (Exception e){
logger.error("异常:" + e);
}
return lineFeatures;
}
public static void geometrysToGeojson(String output, List<? extends Geometry> lineStringList, String lineType){
List<SimpleFeature> lineFeatures = geometrysToGeojson(lineStringList, lineType);
featureToGeojson(output, lineFeatures);
}
public static void geometrysToShp(String output, List<? extends Geometry> lineStringList, String lineType){
List<SimpleFeature> lineFeatures = geometrysToGeojson(lineStringList, lineType);
featureToShp(output, lineFeatures);
}
public static List<LineString> filterLinesByLen(List<LineString> simpleLineList, float filterLen){
List<LineString> filterLineList = new ArrayList<>();
for (LineString simpleLine: simpleLineList) {
if(simpleLine.getLength() >= filterLen){
filterLineList.add(simpleLine);
}
}
return filterLineList;
}
}