开发

geotools之shp文件操作

2017-11-19  本文已影响0人  hehehehe

具体步骤一:

使用工厂函数生成datastore(这应该就是大名鼎鼎的工厂模式吧,我不懂,其实就是之间,父类子类之间转换操作吧应该),得到文件的datastore就相当于c语言的fopen函数拿到操作文件的句柄

具体拿的方式有两种:

第一种方法

FileDataStore store = FileDataStoreFinder.getDataStore(file);

第二种方法

ShapefileDataStore store = (ShapefileDataStore) new ShapefileDataStoreFactory().createDataStore(file);

步骤二:

创建shp文件的结构,也就是schema,告诉他你这个文件有哪些属性,是点线还是面。具体scheme创建方式如下:

创建schema的方法1

SimpleFeatureTypeBuilder tb = new SimpleFeatureTypeBuilder();

tb.setName("shapefile");

tb.add("the_geom", geoType);

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

ds.createSchema(tb.buildFeatureType());

创建schema的方法2

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);

创建schema的方法3

方法3是根据已知文件创建schema

ds.createSchema(SimpleFeatureTypeBuilder.retype(fs.getSchema(), crs));

fs是另一个文件的featuresource,crs是空间坐标系统

步骤三:

有了schema下一步就要生成一个个的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写入文件(官网写法,其实在别处看到还可以用一个writer加一个迭代器,但是也是用了事物transaction,不同的是,属性设置了auto,就先介绍下下面的方法吧,作者在做的时候遇到了无法写入文件的权限问题,网上有方法解决)

核心方法

第一步的到的ds

SimpleFeatureSourcefeatureSource= 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();

至此结束,其中很多部分可以有其他方法,比如featurebuilder中的type,这个type的来源就可以有很多

上一篇下一篇

猜你喜欢

热点阅读