java shapefile 中文乱码_GeoTools读取ESRI ShapeFile中文乱码解决方法

今天在使用Java版GIS开源工具GeoTools读取ShapeFile文件,其中ShapeFile的dbf文件(属性表)中的属性为中文字符,按照官方的案例读取结果显示为乱码。

原始的代码为:

/**

*@description: 使用GeoTools库读取ShapeFile文件

*@author Zhenyu Tan

*@date 2016年8月9日 下午10:15:09

*@version 1.0

*/

public class ShapeFileReader {

public static void main(String[] args) throws Exception {

String filePath = "F:/2016/Data/中国/China/China.shp";

File shapeFile = new File(filePath);

FileDataStore dataStore = FileDataStoreFinder.getDataStore(shapeFile);

// 设置编码后可以正确读取

//((ShapefileDataStore) dataStore).setCharset(Charset.forName("GBK"));

SimpleFeatureSource featureSource = dataStore.getFeatureSource();

SimpleFeatureIterator featureIter = featureSource.getFeatures().features();

// 利用SimpleFeature的迭代器,依次遍历所有的SimpleFeature并输出其属性值

while (featureIter.hasNext()) {

SimpleFeature feature = featureIter.next();

List attributes = feature.getAttributes();

for (Object attr : attributes) {

System.out.println(attr.toString());

}

}

}

}

原因分析:

通过查看ShapefileDataStore的源码可以发现:GeoTools读取ShapeFile文件的默认编码为ISO-8859-1。而我们中文操作系统下ShapeFile文件的默认编码一般为GBK,所以只要告诉ShapefileDataStore使用GBK编码进行解析就OK了。

解决方案一:

设置ShapefileDataStore的解码方式(上面代码片段中以注释的方式给出):

((ShapefileDataStore) dataStore).setCharset(Charset.forName("GBK"));

解决方案二:

手动进行编码转换(治标不治本):

String strAttr = new String(attr.toString().getBytes("ISO-8859-1"), "GBK");

转载自:https://blog.csdn.net/theonegis/article/details/52168672

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值