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<Object> 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

You may also like...

退出移动版