Java在GeoTools组件读取Shp文件属性乱码问题,解决汇总(持续更新,暂时没有完美解决方案)
GeoTools组件在读取Shp文件的属性表信息时,当读取到中文字符时,在代码中的显示为乱码。
问题分析
通过代码分析得到Geotools中打开shapefile文件采用的编码格式为ISO-8859-1,而在读取中文字符中采用ISO-8859-1读取时,便会出现乱码的情况。
1. 手动指定GeoTools读取shp文件的
ShapefileDataStore shape = new ShapefileDataStore(url);
shape.setStringCharset(Charset.forName("GBK"));
2. shp文件中对于中文编码有多种格式,即存在GBK又存在UTF-8
由于ArcGIS版本的问题,在高版本中默认Shp文件的字符编码为UTF-8,而上述代码中指定编码格式为GBK,在代码中需要动态指定一下GBK和UTF-8,文件中的介绍如下: https://www.cnblogs.com/gisoracle/p/8098900.html
我们采用的方法时读取shp文件同名的cpg文件,中存储了当前dbf文件的编码格式,可以通过打开cpg文件的内容,使用文件中的内容作为GeoTools的字符编码格式。
private static String getShapeFileCharsetName(String path) throws Exception {
File pFile = new File(path);
if (pFile.exists() && !pFile.isFile()) {
return "GBK";
}
File file = new File(path);
String encode = "GBK";
BufferedReader reader = null;
try {
reader = new BufferedReader(new FileReader(file));
String tempString = null;
// 一次读入一行,直到读入null为文件结束
while ((tempString = reader.readLine()) != null) {
// 显示行号
if ("UTF-8".equals(tempString.toUpperCase())) {
encode = "UTF-8";
break;
}
break;
}
reader.close();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e1) {
}
}
}
return encode;
}
3. 未完待续…
后续,当我们将dbf文件单独拿到一个文件夹中,使用Excel、Access打开时,他也是可以做到中文字符读取正确(没有乱码),而这是本文中暂时没有get到的点,没有明白基于什么认出文件中的编码格式。