geotools学习:操作shp文件的一些套路

256 阅读1分钟

步骤一、得到dataStore

具体方法有两种 1.

FileDataStore store = FileDataStoreFinder.getDataStore(file);
ShapefileDataStore store = (ShapefileDataStore) new ShapefileDataStoreFactory().createDataStore(file);

步骤二 创建shp文件的结构-schema

具体有三种方法: 1.

SimpleFeatureTypeBuilder tb = new SimpleFeatureTypeBuilder();

tb.setName("shapefile");

tb.add("the_geom", geoType);

tb.add("pid", Long.class);

ds.createSchema(tb.buildFeatureType());

final SimpleFeatureType TYPE = DataUtilities.createType("position",

"the_geom:Point:srid=4326," + // <- the geometry attribute: Point type

"name:String,"// <- a String attribute

"number:Integer"  // a number attribute

);
ds.createSchema(TYPE);
  1. 根据已知文件创建schema
ds.createSchema(SimpleFeatureTypeBuilder.retype(fs.getSchema(), crs));

步骤三,生成一个个feature

//首先需要一个featurebuilder生成一个个的feature

SimpleFeatureBuilder featureBuilder = new SimpleFeatureBuilder(TYPE);

//生成features

List<SimpleFeature> features = new ArrayList<SimpleFeature>()

for (line = reader.readLine(); line != null; line = reader.readLine())

{

        if (line.trim().length() > 0)
        {

        String tokens[] = line.split("\\,");

        double latitude = Double.parseDouble(tokens[0]);

        double longitude = Double.parseDouble(tokens[1]);

        String name = tokens[2].trim();

        int number = Integer.parseInt(tokens[3].trim());

        Point point = geometryFactory.createPoint(new Coordinate(longitude, latitude));

        featureBuilder.add(point);

        featureBuilder.add(name);

        featureBuilder.add(number);

        SimpleFeature feature = featureBuilder.buildFeature(null);

        features.add(feature);



        }

}

步骤四,把features写入shp

第一步的到的ds

SimpleFeatureSource featureSource= ds.getFeatureSource();

Transaction transaction = new DefaultTransaction("create");

SimpleFeatureStore featureStore =(SimpleFeatureStore) featureSource;

SimpleFeatureCollection collection = new ListFeatureCollection(TYPE, features);

featureStore.setTransaction(transaction);

featureStore.addFeatures(collection);

transaction.commit();