guild-book

创建写入新的 shapefile 文件

package com.meic.test;

import java.io.File;
import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;
import org.geotools.data.FeatureWriter;
import org.geotools.data.Transaction;
import org.geotools.data.shapefile.ShapefileDataStore;
import org.geotools.data.shapefile.ShapefileDataStoreFactory;
import org.geotools.feature.simple.SimpleFeatureTypeBuilder;
import org.opengis.feature.simple.SimpleFeature;
import org.opengis.feature.simple.SimpleFeatureType;
import com.vividsolutions.jts.geom.Coordinate;
import com.vividsolutions.jts.geom.GeometryFactory;
import com.vividsolutions.jts.geom.Point;

/**
 * 使用GeoTools写文件示例
 *
 * @author alei
 *
 */
public class WriteShpExample {

    public void write(String filepath) throws Exception {
        Map<String, Serializable> _params = new HashMap<String, Serializable>();
        _params.put(ShapefileDataStoreFactory.URLP.key, new File(filepath).toURI().toURL());
        ShapefileDataStore _dataStore = (ShapefileDataStore) new ShapefileDataStoreFactory().createNewDataStore(_params);
        // 定义图形信息和属性信息
        SimpleFeatureTypeBuilder _typeBuilder = new SimpleFeatureTypeBuilder();
        _typeBuilder.setName("shapefile");
        _typeBuilder.add("the_geom", Point.class);
        _typeBuilder.add("id", Long.class);
        _dataStore.createSchema(_typeBuilder.buildFeatureType());
        // 设置Writer
        FeatureWriter<SimpleFeatureType, SimpleFeature> _writer = _dataStore.getFeatureWriter(_dataStore.getTypeNames()[0], Transaction.AUTO_COMMIT);
        // 写下一条
        SimpleFeature _feature = _writer.next();
        _feature.setAttribute("the_geom", new GeometryFactory().createPoint(new Coordinate(116.123, 39.345)));
        _feature.setAttribute("id", 11111111);
        _writer.write();
        _writer.close();
        _dataStore.dispose();
    }

}