GeoTools支持中文的解决方法

本文介绍如何使用 GeoTools 2.4 版本解决读取 shp 文件时遇到的中文乱码问题,并提供两种示例代码。

【网址】:http://www.blogjava.net/sinoly/archive/2007/09/30/geotools_shape.html 

困扰了好几天,一直在尝试各种方法解决Geotools读取shp格式对中文编码的问题。可是昨天一个无意的举动居然让我发觉自己做了太多的无用之功。仔细的看了JavaDoc以及shapefile源代码之后,可以可以明显的看到ShapefileDataStore的构造函数已经发生了很大的变化:
    

public static final Charset DEFAULT_STRING_CHARSET = Charset.forName("ISO-8859-1");


    这个是ShapefileDataStore对象中定义的字符编码。也正是由于其使用ISO-8859-1编码作为默认编码,所以一直以来,解决geotools抑或geoserver的中文问题总是连绵不绝。
   来看看我在2.4中看到的ShapefileDataStore的新的构造函数(当然,贝塔和我聊天说过好像2.3也是作出了同样修改的,可惜我没下2.3的源码,呵呵,但是2.2以前的版本这一块貌似是不同的。权当其是2.4中的“新增”之处吧)

 1     public ShapefileDataStore(URL url, boolean useMemoryMappedBuffer)
 2         throws MalformedURLException
 3     {
 4         this(url, useMemoryMappedBuffer, DEFAULT_STRING_CHARSET);
 5     }
 6
 7     public ShapefileDataStore(URL url, boolean useMemoryMappedBuffer, Charset dbfCharset)
 8         throws MalformedURLException
 9     {
10         readWriteLock = new Lock();
11         namespace = null;
12         this.useMemoryMappedBuffer = true;
13         String filename = null;
14         shpURL = ShapefileDataStoreFactory.toShpURL(url);
15         dbfURL = ShapefileDataStoreFactory.toDbfURL(url);
16         shxURL = ShapefileDataStoreFactory.toShxURL(url);
17         prjURL = ShapefileDataStoreFactory.toPrjURL(url);
18         xmlURL = ShapefileDataStoreFactory.toXmlURL(url);
19         this.dbfCharset = dbfCharset;
20     }

     
   



     列下使用Geotools 2.4操作shp格式的代码如下:
    代码1:

 1 public class ReadShape  {
 2     public static void main(String[] args) 
 3         throws FileNotFoundException,MalformedURLException,IOException{
 4         
 5         File shpFile=new File("shp/市区地物_point.dbf");
 6         ShapefileDataStore shpDataStore=new ShapefileDataStore(shpFile.toURL());
 7         shpDataStore.setStringCharset(Charset.forName("GBK"));
 8         FeatureSource fs=shpDataStore.getFeatureSource();
 9         FeatureCollection collection = fs.getFeatures();
10         FeatureIterator iterator = collection.features();
11         int numOfAttr=0;
12         try {
13            while( iterator.hasNext() ){
14                 Feature feature = iterator.next();
15                 numOfAttr = feature.getNumberOfAttributes();
16                 for(int i=0;i < numOfAttr ;i++){
17                     String temp =feature.getAttribute(i).toString();
18                      System.out.print(temp+"/t");
19                 }
20                 
21                 System.out.println();
22            }
23         }
24         finally {
25            iterator.close();
26         }
27     }
28 }

    代码2:

 1 public class ReadSHP  {
 2     public static void main(String[] args) 
 3         throws FileNotFoundException,MalformedURLException,IOException{
 4
 5         //初始化FileChannel对象
 6         FileChannel in = new FileInputStream("shp/市区地物_point.dbf").getChannel();
 7         DbaseFileReader dr=new DbaseFileReader(in, true,Charset.forName("UTF-8"));
 8         DbaseFileHeader dh = dr.getHeader();
 9         int fields = dh.getNumFields();
10         for(int i=0;i < fields ;i++){
11             System.out.print(dh.getFieldName(i)+" ");//打印当前属性名
12         }
13         System.out.print("/n");
14         while(dr.hasNext()){
15             DbaseFileReader.Row row  = dr.readRow();
16              for (int i =0;i<fields;i++){
17                      Object data  = row.read(i);
18                      if(dh.getFieldName(i).equals("NAME")){
19                             System.out.print(data);
20                     }else{
21                             System.out.print(data);
22                     }
23                     System.out.print("/t");
24             }
25             System.out.println();
26         }
27         dr.close();
28     }
29 }
org.geotools org.geotools.arcsde org.geotools.arcsde.data org.geotools.arcsde.data.versioning org.geotools.arcsde.data.view org.geotools.arcsde.filter org.geotools.arcsde.gce org.geotools.arcsde.gce.band org.geotools.arcsde.gce.imageio org.geotools.arcs de.gce.producer org.geotools.arcsde.pool org.geotools.axis org.geotools.brewer.color org.geotools.coverage org.geotools.coverage.grid org.geotools.coverage.grid.io org.geotools.coverage.grid.io.imageio org.geotools.coverage.io org.geotools.coverage.processing org.geotools.coverage.processing.operation org.geotools.data org.geotools.data.collection org.geotools.data.crs org.geotools.data.db2 org.geotools.data.db2.filter org.geotools.data.dir org.geotools.data.gml org.geotools.data.gpx org.geotools.data.gpx.temporal org.geotools.data.h2 org.geotools.data.jdbc org.geotools.data.jdbc.attributeio org.geotools.data.jdbc.datasource org.geotools.data.jdbc.fidmapper org.geotools.data.jdbc.referencing org.geotools.data.memory org.geotools.data.mif org.geotools.data.mysql org.geotools.data.oracle org.geotools.data.oracle.attributeio org.geotools.data.oracle.referencing org.geotools.data.oracle.sdo org.geotools.data.ows org.geotools.data.postgis org.geotools.data.postgis.attributeio org.geotools.data.postgis.collection org.geotools.data.postgis.fidmapper org.geotools.data.postgis.referencing org.geotools.data.property org.geotools.data.shapefile org.geotools.data.shapefile.dbf org.geotools.data.shapefile.indexed org.geotools.data.shapefile.indexed.attribute org.geotools.data.shapefile.prj org.geotools.data.shapefile.shp org.geotools.data.shapefile.shp.xml org.geotools.data.store org.geotools.data.tiger org.geotools.data.view org.geotools.data.vpf org.geotools.data.vpf.exc org.geotools.data.vpf.file org.geotools.data.vpf.ifc org.geotools.data.vpf.io org.geotools.data.vpf.readers org.geotools.data.vpf.util org.geotools.data.wfs org.geotools.data.wms org.geotools.data.wms.request org.geotools.data.wms.response org.geotools.data.wms.xml org.geotools.demo org.geotools.demo.data org.geotools.demo.example org.geotools.demo.features org.geotools.demo.geometry org.geotools.demo.introduction org.geotools.demo.jts org.geotools.demo.libraryJTS org.geotools.demo.main org.geotools.demo.mappane org.geotools.demo.metadata.example org.geotools.demo.postgis org.geotools.demo.swing org.geotools.demo.swing.process org.geotools.demo.widgets org.geotools.demo.xml org.geotools.display.canvas org.geotools.display.canvas.map org.geotools.display.event org.geotools.display.geom org.geotools.display.style org.geotools.factory org.geotools.feature org.geotools.feature.collection org.geotools.feature.simple org.geotools.feature.type org.geotools.feature.visitor org.geotools.filter org.geotools.filter.capability org.geotools.filter.expression org.geotools.filter.function org.geotools.filter.function.math org.geotools.filter.identity org.geotools.filter.parser org.geotools.filter.spatial org.geotools.filter.text.cql2 org.geotools.filter.text.txt org.geotools.filter.v1_0 org.geotools.filter.v1_0.capabilities org.geotools.filter.v1_1 org.geotools.filter.v1_1.capabilities org.geotools.filter.visitor org.geotools.gce.arcgrid org.geotools.gce.geotiff org.geotools.gce.geotiff.crs_adapters org.geotools.gce.geotiff.IIOMetadataAdpaters org.geotools.gce.geotiff.IIOMetadataAdpaters.utils org.geotools.gce.geotiff.IIOMetadataAdpaters.utils.codes org.geotools.gce.gtopo30 org.geotools.gce.image org.geotools.gce.imagemosaic org.geotools.gce.imagepyramid org.geotools.geometry org.geotools.geometry.array org.geotools.geometry.coordinatesequence org.geotools.geometry.iso org.geotools.geometry.iso.aggregate org.geotools.geometry.iso.complex org.geotools.geometry.iso.coordinate org.geotools.geometry.iso.index org.geotools.geometry.iso.index.quadtree org.geotools.geometry.iso.io org.geotools.geometry.iso.io.wkt org.geotools.geometry.iso.operation org.geotools.geometry.iso.operation.overlay org.geotools.geometry.iso.operation.relate org.geotools.geometry.iso.primitive org.geotools.geometry.iso.root org.geotools.geometry.iso.topograph2D org.geotools.geometry.iso.topograph2D.index org.geotools.geometry.iso.topograph2D.util org.geotools.geometry.iso.util org.geotools.geometry.iso.util.algorithm2D org.geotools.geometry.iso.util.algorithmND org.geotools.geometry.iso.util.elem2D org.geotools.geometry.iso.util.interpolation org.geotools.geometry.iso.util.topology org.geotools.geometry.jts org.geotools.geometry.jts.coordinatesequence org.geotools.geometry.jts.spatialschema org.geotools.geometry.jts.spatialschema.geometry org.geotools.geometry.jts.spatialschema.geometry.aggregate org.geotools.geometry.jts.spatialschema.geometry.complex org.geotools.geometry.jts.spatialschema.geometry.geometry org.geotools.geometry.jts.spatialschema.geometry.primitive org.geotools.geometry.text org.geotools.gml org.geotools.gml.producer org.geotools.gml2 org.geotools.gml2.bindings org.geotools.gml3 org.geotools.gml3.bindings org.geotools.gml3.bindings.smil org.geotools.gml3.smil org.geotools.gpx org.geotools.gpx.bean org.geotools.gpx.binding org.geotools.graph.build org.geotools.graph.build.basic org.geotools.graph.build.feature org.geotools.graph.build.line org.geotools.graph.build.opt org.geotools.graph.build.polygon org.geotools.graph.io org.geotools.graph.io.standard org.geotools.graph.path org.geotools.graph.structure org.geotools.graph.structure.basic org.geotools.graph.structure.line org.geotools.graph.structure.opt org.geotools.graph.traverse org.geotools.graph.traverse.basic org.geotools.graph.traverse.standard org.geotools.graph.util org.geotools.graph.util.delaunay org.geotools.graph.util.geom org.geotools.graph.util.graph org.geotools.gui.headless org.geotools.gui.swing org.geotools.gui.swing.contexttree org.geotools.gui.swing.contexttree.column org.geotools.gui.swing.contexttree.node org.geotools.gui.swing.contexttree.popup org.geotools.gui.swing.contexttree.renderer org.geotools.gui.swing.crschooser org.geotools.gui.swing.datachooser org.geotools.gui.swing.datachooser.model org.geotools.gui.swing.demo org.geotools.gui.swing.event org.geotools.gui.swing.filter org.geotools.gui.swing.icon org.geotools.gui.swing.image org.geotools.gui.swing.map.map2d org.geotools.gui.swing.map.map2d.control org.geotools.gui.swing.map.map2d.decoration org.geotools.gui.swing.map.map2d.event org.geotools.gui.swing.map.map2d.handler org.geotools.gui.swing.map.map2d.listener org.geotools.gui.swing.map.map2d.strategy org.geotools.gui.swing.misc org.geotools.gui.swing.misc.filter org.geotools.gui.swing.misc.Render org.geotools.gui.swing.process org.geotools.gui.swing.propertyedit org.geotools.gui.swing.propertyedit.filterproperty org.geotools.gui.swing.propertyedit.model org.geotools.gui.swing.propertyedit.styleproperty org.geotools.gui.swing.referencing org.geotools.gui.swing.style org.geotools.gui.swing.style.sld org.geotools.gui.swing.table org.geotools.gui.swing.tree org.geotools.image org.geotools.image.io org.geotools.image.io.metadata org.geotools.image.io.mosaic org.geotools.image.io.netcdf org.geotools.image.io.stream org.geotools.image.io.text org.geotools.image.jai org.geotools.image.palette org.geotools.index org.geotools.index.quadtree org.geotools.index.quadtree.fs org.geotools.index.rtree org.geotools.index.rtree.cachefs org.geotools.index.rtree.database org.geotools.index.rtree.database.mysql org.geotools.index.rtree.fs org.geotools.index.rtree.memory org.geotools.io org.geotools.jdbc org.geotools.kml org.geotools.kml.bindings org.geotools.legend org.geotools.map org.geotools.map.event org.geotools.math org.geotools.measure org.geotools.metadata org.geotools.metadata.iso org.geotools.metadata.iso.citation org.geotools.metadata.iso.constraint org.geotools.metadata.iso.content org.geotools.metadata.iso.distribution org.geotools.metadata.iso.extent org.geotools.metadata.iso.identification org.geotools.metadata.iso.lineage org.geotools.metadata.iso.maintenance org.geotools.metadata.iso.quality org.geotools.metadata.iso.spatial org.geotools.metadata.sql org.geotools.nature org.geotools.openoffice org.geotools.ows org.geotools.ows.bindings org.geotools.ows.v1_1 org.geotools.parameter org.geotools.process org.geotools.process.impl org.geotools.process.literal org.geotools.referencing org.geotools.referencing.crs org.geotools.referencing.cs org.geotools.referencing.datum org.geotools.referencing.example org.geotools.referencing.factory org.geotools.referencing.factory.epsg org.geotools.referencing.factory.wms org.geotools.referencing.operation org.geotools.referencing.operation.builder org.geotools.referencing.operation.matrix org.geotools.referencing.operation.projection org.geotools.referencing.operation.transform org.geotools.referencing.piecewise org.geotools.referencing.wkt org.geotools.renderer org.geotools.renderer.i18n org.geotools.renderer.lite org.geotools.renderer.lite.gridcoverage2d org.geotools.renderer.shape org.geotools.renderer.shape.shapehandler.jts org.geotools.renderer.shape.shapehandler.simple org.geotools.renderer.style org.geotools.repository org.geotools.repository.adaptable org.geotools.repository.defaults org.geotools.repository.postgis org.geotools.repository.property org.geotools.repository.shapefile org.geotools.repository.styling org.geotools.repository.wfs org.geotools.repository.wms org.geotools.sld org.geotools.sld.bindings org.geotools.styling org.geotools.styling.visitor org.geotools.svg org.geotools.test org.geotools.text org.geotools.text.filter org.geotools.util org.geotools.util.logging org.geotools.utils org.geotools.utils.coveragetiler org.geotools.utils.imagemosaic org.geotools.utils.imageoverviews org.geotools.utils.imagepyramid org.geotools.utils.progress org.geotools.validation org.geotools.validation.attributes org.geotools.validation.dto org.geotools.validation.network org.geotools.validation.relate org.geotools.validation.spatial org.geotools.validation.xml org.geotools.wfs org.geotools.wfs.bindings org.geotools.wfs.protocol org.geotools.wfs.v_1_0_0.data org.geotools.wfs.v_1_1_0.data org.geotools.xlink org.geotools.xml org.geotools.xml.filter org.geotools.xml.gml org.geotools.xml.handlers org.geotools.xml.handlers.xsi org.geotools.xml.impl org.geotools.xml.impl.jxpath org.geotools.xml.schema org.geotools.xml.schema.impl org.geotools.xml.styling org.geotools.xml.test org.geotools.xml.transform org.geotools.xml.wfs org.geotools.xml.xLink org.geotools.xml.xsi org.geotools.xs org.geotools.xs.bindings org.geotools.xs.facets
<think>嗯,用户这次的问题很具体:解决GeoTools导入PostGIS时的中文乱码。看来用户正在处理空间数据的中文编码问题,可能是个GIS开发人员或者数据处理工程师。从引用内容看,用户已经做了功课,知道乱码根源在GeoTools读取shapefile时对dbf文件的编码处理有问题。引用[1]和[2]都提到GeoTools的shapefile模块默认用ISO-8859-1读取dbf,导致中文乱码。用户现在想跳过shapefile直接导入PostGIS,这确实是更彻底的解决方案。用户可能已经尝试过修改shapefile参数但没成功,所以想绕过这个坑。ta的深层需求应该是保证中文数据从源头到入库全流程可读。需要特别注意:用户引用[5]提到过创建geometry对象,说明ta应该写过Java代码操作GeoTools,所以方案需要提供API级别的具体实现。结合五个引用,重点看三点:第一,引用[1][2]确认乱码根源在dbf读取阶段;第二,引用[3]中SLD指定字体的方案不适用当前场景;第三,引用[4][5]显示GeoTools操作PostGIS需要通过Feature读写。核心解决思路应该是控制数据流动全程的编码:入库前必须确保Java字符串是正确编码的UTF-8——这需要检查shapefile的真实编码(可能是GBK),用Charset.forName显式指定,像引用[2]暗示的那样。之后用PostGIS扩展保证数据库支持UTF-8,最后在GeoTools连接池里强制UTF-8。用户可能会遇到的坑是:某些旧版shapefile用GB2312编码,而GeoTools24版后支持传入charset参数。需要在回复里强调版本差异,避免用户踩坑。另外PostGIS的initdb初始化编码容易被忽略,要特别提醒。考虑到用户需要实操,回复要包含四部分:明确乱码原理(为什么)、分阶段解决方案(怎么做)、关键代码示例(动手参考)、扩展方案(万一不行)。尤其要给出GeoTools读取shapefile时显式指定编码的代码片段,像newShapefileDataStore(file,true,Charset.forName("GBK"))这样的具体写法。用户似乎比较着急,回复要把最直接的PostGIS入库方案放前面,补充说明放后面。最后主动提出延伸问题,帮ta预防后续可能遇到的显示乱码问题。</think> 基于引用信息和GeoTools特性,以下是解决GeoTools导入PostGIS中文乱码的完整方案: ### 🔧 核心解决方案(分步实施) 1. **源头编码控制** - 在读取Shapefile时**显式指定DBF编码**(GBK/UTF-8),覆盖GeoTools默认的ISO-8859-1: ```java // 关键代码:强制指定中文编码 ShapefileDataStore shpDataStore = new ShapefileDataStore(file.toURL()); shpDataStore.setCharset(Charset.forName("GBK")); // 根据实际文件编码调整 ``` 2. **PostGIS库配置验证** - 登录数据库执行 `SHOW server_encoding;` - 若编码非`UTF8`,需重建数据库: ```sql CREATE DATABASE gisdb WITH ENCODING='UTF8' TEMPLATE=template0; ``` 3. **JDBC连接强化配置** 在GeoTools连接参数中添加编码强制声明: ```java Map<String, Object> params = new HashMap<>(); params.put("dbtype", "postgis"); params.put("host", "localhost"); params.put("port", 5432); params.put("schema", "public"); params.put("database", "gisdb"); params.put("user", "postgres"); params.put("passwd", "password"); // ⚠️ 关键参数:驱动层强制UTF-8 params.put("ConnectionParameters", "characterEncoding=utf8"); ``` 4. **写入时类型检查** ```java feature.getProperty("name").setValue("中文测试"); // 写入前确保字符串无乱码 featureStore.modifyFeatures(/*...*/); // 提交到PostGIS ``` ### 🛠 补充措施 - **Shapefile预处理工具** 使用QGIS或`ogr2ogr`转换编码: ```bash ogr2ogr -f "ESRI Shapefile" -lco ENCODING=UTF-8 output.shp input.shp ``` - **版本验证** GeoTools ≥24.0版本对编码支持更完善,依赖配置: ```xml <dependency> <groupId>org.geotools</groupId> <artifactId>gt-shapefile</artifactId> <version>24.0</version> <!-- 优化了编码处理 --> </dependency> ``` ### 📊 故障排查路径 ```mermaid graph LR A[乱码现象] --> B{数据流环节} B --> C[[Shapefile读取]] B --> D[[PostGIS写入]] B --> E[[客户端显示]] C -->|编码未指定| F[强制setCharset] D -->|库编码非UTF8| G[重建数据库] E -->|应用层乱码| H[检查JDBC连接参数] ``` ### ❓ 延伸问题 1. 如何验证Shapefile的真实编码而非文件声明? 2. PostGIS导入后前端地图仍显示乱码该如何处理? 3. 除GBK/UTF-8外,哪些中文编码可能需特殊处理? 4. GeoTools在处理Big5编码时有何注意事项? > 通过上述流程可根本解决编码问题。实践表明,明确指定各环节编码(尤其`setCharset()`和JDBC参数)是关键[^1][^2][^5]。若仍遇异常,建议使用十六进制编辑器验证DBF文件头编码标识。
评论 1
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值