geoTools向shp文件中写数据

本文介绍如何使用GeoTools库创建并写入带有地理位置信息的Shapefile文件。通过定义特征类型、构造几何对象及属性,最终将数据保存到本地磁盘。此示例展示了完整的写入流程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

package test;

import java.io.File;
import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;

import org.geotools.data.DataUtilities;
import org.geotools.data.DefaultTransaction;
import org.geotools.data.Transaction;
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.FeatureCollections;
import org.geotools.feature.simple.SimpleFeatureBuilder;
import org.geotools.referencing.crs.DefaultGeographicCRS;
import org.junit.Test;
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;

//使用geotools2.7.2
public class WriteData {
	
    @Test
    public void write2() {  
        try{    
            //定义属性  
            final SimpleFeatureType TYPE = DataUtilities.createType("Location",  
                "location:Point," + // <- the geometry attribute: Point type  
                "POIID:String," + // <- a String attribute  
                "MESHID:String," + // a number attribute  
                "OWNER:String"  
            );  
            SimpleFeatureCollection collection = FeatureCollections.newCollection();  
            GeometryFactory geometryFactory = new GeometryFactory();  
            SimpleFeatureBuilder featureBuilder = new SimpleFeatureBuilder(TYPE);  
      
            double latitude = Double.parseDouble("116.123456789");  
            double longitude = Double.parseDouble("39.120001");  
            String POIID = "2050003092";  
            String MESHID = "0";  
            String OWNER = "340881";  
            Point point = geometryFactory.createPoint(new Coordinate(longitude, latitude));  
            Object[] obj = {point, POIID, MESHID, OWNER};  
            SimpleFeature feature = featureBuilder.buildFeature(null, obj);  
            collection.add(feature);  
            feature = featureBuilder.buildFeature(null, obj);  
            collection.add(feature);  
            File newFile = new File("D:/newPoi.shp");  
            ShapefileDataStoreFactory dataStoreFactory = new ShapefileDataStoreFactory();  
            Map<String, Serializable> params = new HashMap<String, Serializable>();  
            params.put("url", newFile.toURI().toURL());  
            params.put("create spatial index", Boolean.TRUE);  
            ShapefileDataStore newDataStore = (ShapefileDataStore) dataStoreFactory.createNewDataStore(params);  
            newDataStore.createSchema(TYPE);  
            newDataStore.forceSchemaCRS(DefaultGeographicCRS.WGS84);  
      
            Transaction transaction = new DefaultTransaction("create");  
            String typeName = newDataStore.getTypeNames()[0];  
            SimpleFeatureSource featureSource = newDataStore.getFeatureSource(typeName);  
      
            if (featureSource instanceof SimpleFeatureStore) {  
                SimpleFeatureStore featureStore = (SimpleFeatureStore) featureSource;  
                featureStore.setTransaction(transaction);  
                try {  
                    featureStore.addFeatures(collection);  
                    transaction.commit();  
                } catch (Exception problem) {  
                    problem.printStackTrace();  
                transaction.rollback();  
                } finally {  
                    transaction.close();  
                }  
            } else {  
                System.out.println(typeName + " does not support read/write access");  
            }  
        } catch (Exception e) {  
            e.printStackTrace();  
        }  
    }  
}

在使用Geotoolsshp文件时,中文属性乱码问题可能是因为编码不一致所致。可以尝试在写入shp文件之前,设置相应的编码格式,例如: ```java // 创建shapefile数据存储对象 Map<String, Serializable> params = new HashMap<>(); params.put("url", new File("path/to/shapefile.shp").toURI().toURL()); params.put("create spatial index", Boolean.TRUE); DataStore newDataStore = DataStoreFinder.getDataStore(params); // 定义shapefile属性字段 SimpleFeatureType TYPE = DataUtilities.createType("Location", "the_geom:Point:srid=4326," + // 必须包含一个几何属性 "name:String"); // 设置中文属性字段编码 ((ShapefileDataStore)newDataStore).setCharset(Charset.forName("GBK")); // 创建要素并写入shapefile文件 SimpleFeatureBuilder featureBuilder = new SimpleFeatureBuilder(TYPE); GeometryFactory geometryFactory = JTSFactoryFinder.getGeometryFactory(); Point point = geometryFactory.createPoint(new Coordinate(116.404, 39.915)); featureBuilder.add(point); featureBuilder.add("北京市"); SimpleFeature feature = featureBuilder.buildFeature(null); Transaction transaction = newDataStore.getTransaction(); SimpleFeatureSource featureSource = newDataStore.getFeatureSource(TYPE.getName().getLocalPart()); if (featureSource instanceof SimpleFeatureStore) { SimpleFeatureStore featureStore = (SimpleFeatureStore) featureSource; featureStore.setTransaction(transaction); try { featureStore.addFeatures(DataUtilities.collection(feature)); transaction.commit(); } catch (Exception e) { transaction.rollback(); } finally { transaction.close(); } } newDataStore.dispose(); ``` 在上述代码中,通过`((ShapefileDataStore)newDataStore).setCharset(Charset.forName("GBK"));`来设置中文属性字段的编码格式为GBK。可以根据实际情况进行调整。
评论 7
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值