title: (十一)Shapefile编码(下)
date: 2021-05-12 17:24:46
tags:
- GeoSpark
- GIS
shp文件编码转换
方法1:利用FME转换
-
首先打开FME Workbench,新建一个空白工程
-
添加一个Reader,格式选择Esri Shapefile,然后点击
Parameters
按钮,在
Character Encoding
一栏选择对应的编码(如果不确定,这里留空白就好,FME会自动匹配),点击OK,选择shp文件路径
image.png
image.png
-
在添加一个Writer,格式仍然选择为Esri Shapefile,然后和第2步一样,点击
Parameters
选择编码,选择输出路径,点击OK,最后将这两个转换器连接在一起
image.png
-
使用快捷键F5或者点击菜单栏运行按钮运行该模板,完成编码转换。
image.png
方法2
可以利用geotools,具体代码如下。Geospark已经内置了geotools,无需在添加相关依赖,我们先利用源dbf文件编码读取shp文件,然后在用新的编码将数据写入到shp中,就完成了编码转换,本案例也可以作为利用geotools读写shp参考。
import org.geotools.data.*;
import org.geotools.data.shapefile.ShapefileDataStore;
import org.geotools.data.shapefile.ShapefileDataStoreFactory;
import org.geotools.data.simple.SimpleFeatureSource;
import org.geotools.data.simple.SimpleFeatureStore;
import org.opengis.feature.simple.SimpleFeature;
import org.opengis.feature.simple.SimpleFeatureType;
import java.io.*;
import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.Map;
public class Learn10 {
public static void main(String[] args) throws Exception {
Charset sourceCharset = Charset.forName("GBK");
Charset targetCharset = Charset.forName("UTF-8");
Map<String, Object> parm = new HashMap<>();
// 待转换源SHP文件
parm.put("url", Learn10.class.getResource("/parks/Parks.shp"));
ShapefileDataStore reader = (ShapefileDataStore)DataStoreFinder.getDataStore(parm);
ShapefileDataStoreFactory factory = new ShapefileDataStoreFactory();
Map<String, Serializable> dest = new HashMap<>();
// 转换后目标SHP存储文件
dest.put("url", new File("./Parks-UTF8.shp").toURL());
ShapefileDataStore writer = (ShapefileDataStore)factory.createDataStore(dest);
writer.createSchema(reader.getSchema()); // 复制源SHP的结构(包含坐标系)
writer.setCharset(targetCharset);
Transaction t = new DefaultTransaction("Add");
SimpleFeatureStore featureStore = (SimpleFeatureStore)writer.getFeatureSource();
featureStore.setTransaction(t);
try {
featureStore.addFeatures(reader.getFeatureSource().getFeatures());
t.commit();
}catch (Exception e){
t.rollback();
}finally {
t.close();
}
}
}
本节代码可以在https://github.com/scially/GeosparkBook找到(Learn10.java)
参考链接:https://www.jianshu.com/p/f5cc5dc63741