java shapefile 中文乱码_GeoTools操作Shape格式文件
需要从Web系统中导出Shape格式数据文件,并使用AicMap打开。
中间件在系统中扮演连接数据和服务的角色。GeoTools承担了从各种数据源(如PostGIS,GML,Shapefile,WFS)读取数据并将数据标准化的工作。Feature接口就定义在GeoTools中,不同数据源的数据读出后被统一成包含一个Geometry成员(定义在JTS中)的Feature接口的实现。这样,进一步的操作只需面向Feature即可,省去了高层软件对于不同数据源的解读过程。另外,GeoTools还是OpenGIS标准的全面实现,其中包括Filter、坐标转换、GML。
GeoTools官网
http://geotools.org
GeoTools API
http://docs.geotools.org/latest/javadocs/
GeoTools 中央仓库地址
geotools-repos
GeoTools Repository
http://download.osgeo.org/webdav/geotools/
geotools2-repos
GeoTools2 Repository
http://repo1.maven.org/maven2/
GeoTools Jar
gt-referencing-2.7.2
gt-shapefile-2.7.2
gt-api-2.7.2
gt-main-2.7.2
gt-opengis-2.7.2
gt-metadata-2.7.2
gt-data-2.7.2
jts-1.11
jsr-275-1.0-beta-2
jai_core-1.1.3
Maven(gt-referencing-2.7.2从中央仓库获取有问题,故改成本地Jar,具体视自己机器排查)
org.geotools
gt-api
2.7.2
org.geotools
gt-main
2.7.2
org.geotools
gt-opengis
2.7.2
org.geotools
gt-shapefile
2.7.2
com.vividsolutions
jts
1.11
org.geotools
gt-metadata
2.7.2
org.geotools
gt-data
2.7.2
javax.measure
jsr-275
1.0.0
org.geotools
gt-referencing
2.7.2
system
${project.basedir}/lib/gt-referencing-2.7.2.jar
javax.media
jai_core
1.1.3
GeoTools简单说明
下面将分为2.7.2和10.0两种版本的写法演示,不同版本之间的写法略有不同。
shape格式文件最少包含3个文件,他们的后缀是:.shp, .dbf, .shx。
.shp存储地理形状和位置信息,.dbf存储属性信息,.shx是索引文件。
在读取文件和输出文件的时候千万要注意到中文字符乱码问题,测试发现读取和输出的时候使用GBK或UTF-8,不对字符串进行转码,因为没有用,在对应方法中设置数据格式才对。(ShapefileDataStore的setStringCharset(Charset.forName("GBK"));等方法)
GeoTools-2.7.2-单独读取DBF文件(未测试)
public void readDBF(String path) {
DbaseFileReader reader = null;
try {
reader = new DbaseFileReader(new ShpFiles(path), false, Charset.forName("GBK"));
DbaseFileHeader header = reader.getHeader();
int numFields = header.getNumFields();
//迭代读取记录
while (reader.hasNext()) {
try {
Object[] entry = reader.readEntry();
for (int i=0; i
String title = header.getFieldName(i);
Object value = entry[i];
System.out.println(title+"="+value);
}
} catch (Exception e) {
e.printStackTrace();
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (reader != null) {
//关闭
try {reader.close();} catch (Exception e) {}
}
}
}
GeoTools-2.7.2-读取3个文件,以point和polygon为例,WjPoint和WjPolygon为自定义实体对象,返回全部点和面的数据(已测试可用)
public Map readSHP(String path) {
Map map = new HashMap();
List wjPointList = new ArrayList();
List wjPolygonList = new ArrayList();
ShapefileDataStore shpDataStore = null;
try{
File shpfile = new File(path);
shpDataStore = new ShapefileDataStore(shpfile.toURI().toURL());
shpDataStore.setStringCharset(Charset.forName("GBK"));
String typeName = shpDataStore.getTypeNames()[0];
FeatureSource featureSource = null;
featureSource = (FeatureSource)shpDataStore.getFeatureSource(typeName);
FeatureCollection result = featureSource.getFeatures();
System.out.println(result.size());
FeatureIterator itertor = result.features();
while(itertor.hasNext()){
SimpleFeature feature = itertor.next();
Collection p = feature.getProperties();
Iterator it = p.iterator();
while(it.hasNext()) {
Property pro = it.next();
if (pro.getValue() instanceof Point) {
System.out.println("PointX = " + ((Point)(pro.getValue())).getX());
System.out.println("PointY = " + ((Point)(pro.getValue())).getY());
WjPoint wjPoint = new WjPoint();
wjPoint.setShp(((Point)pro.getValue()).toString());
wjPointList.add(wjPoint);
} else if (pro.getValue() instanceof MultiPolygon) {
WjPolygon wjPolygon = new WjPolygon();
wjPolygon.setShp(((Polygon)((MultiPolygon)pro.getValue()).getGeometryN(0)).toString());
wjPolygonList.add(wjPolygon);
} else {
System.out.println(pro.getName() + " = " + pro.getValue());
}
}
}
itertor.close();
shpDataStore.dispose();
shpfile.exists();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch(IOException e) { e.printStackTrace(); }
map.put("wjPointList", wjPointList);
map.put("wjPolygonList", wjPolygonList);
return map;
}
GeoTools-2.7.2-写shape文件,以point为例(已测试可用)
package com.shp.mapsay;
import java.io.File;
import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;
import org.geotools.data.DataUtilities;
import org.geotools.data.DefaultTransaction;
import org.geotools.data.Transaction;
import org.geotools.data.shapefile.ShapefileDataStore;
import org.geotools.data.shapefile.ShapefileDataStoreFactory;
import org.geotools.data.simple.SimpleFeatureCollection;
import org.geotools.data.simple.SimpleFeatureSource;
import org.geotools.data.simple.SimpleFeatureStore;
import org.geotools.feature.FeatureCollections;
import org.geotools.feature.simple.SimpleFeatureBuilder;
import org.geotools.referencing.crs.DefaultGeographicCRS;
import org.opengis.feature.simple.SimpleFeature;
import org.opengis.feature.simple.SimpleFeatureType;
import com.vividsolutions.jts.geom.Coordinate;
import com.vividsolutions.jts.geom.GeometryFactory;
import com.vividsolutions.jts.geom.Point;
public class test1 {
public static void main(String[] args) {
try{
//定义属性
final SimpleFeatureType TYPE = DataUtilities.createType("Location",
"location:Point," + //
"POIID:String," + //
"MESHID:String," + // a number attribute
"OWNER:String"
);
SimpleFeatureCollection collection = FeatureCollections.newCollection();
GeometryFactory geometryFactory = new GeometryFactory();
SimpleFeatureBuilder featureBuilder = new SimpleFeatureBuilder(TYPE);
double latitude = Double.parseDouble("19.968");
double longitude = Double.parseDouble("110.402");
String POIID = "2050003092";
String MESHID = "0";
String OWNER = "不睡觉假装王祖贤";
/* Longitude (= x coord) first ! */
Point point = geometryFactory.createPoint(new Coordinate(longitude, latitude));
Object[] obj = {point, POIID, MESHID, OWNER};
// SimpleFeature只能创建一次
SimpleFeature feature = featureBuilder.buildFeature(null, obj);
collection.add(feature);
feature = featureBuilder.buildFeature(null, obj);
collection.add(feature);
File newFile = new File("D:/newPoi1.shp");
ShapefileDataStoreFactory dataStoreFactory = new ShapefileDataStoreFactory();
Map params = new HashMap();
params.put("url", newFile.toURI().toURL());
params.put("create spatial index", Boolean.TRUE);
ShapefileDataStore newDataStore = (ShapefileDataStore) dataStoreFactory.createNewDataStore(params);
newDataStore.createSchema(TYPE);
newDataStore.forceSchemaCRS(DefaultGeographicCRS.WGS84);
newDataStore.setStringCharset(Charset.forName("UTF-8"));
Transaction transaction = new DefaultTransaction("create");
String typeName = newDataStore.getTypeNames()[0];
SimpleFeatureSource featureSource = newDataStore.getFeatureSource(typeName);
if (featureSource instanceof SimpleFeatureStore) {
SimpleFeatureStore featureStore = (SimpleFeatureStore) featureSource;
featureStore.setTransaction(transaction);
try {
featureStore.addFeatures(collection);
transaction.commit();
} catch (Exception problem) {
problem.printStackTrace();
transaction.rollback();
} finally {
transaction.close();
}
} else {
System.out.println(typeName + " does not support read/write access");
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
GeoTools-10.0-读Shp文件(图形信息+属性信息)
import java.io.File;
import java.nio.charset.Charset;
import java.util.Iterator;
import org.geotools.data.shapefile.ShapefileDataStore;
import org.geotools.data.shapefile.ShapefileDataStoreFactory;
import org.geotools.data.simple.SimpleFeatureIterator;
import org.geotools.data.simple.SimpleFeatureSource;
import org.opengis.feature.Property;
import org.opengis.feature.simple.SimpleFeature;
public class ShpNew {
public static void main(String[] args) {
ShapefileDataStoreFactory dataStoreFactory = new ShapefileDataStoreFactory();
try {
ShapefileDataStore sds = (ShapefileDataStore)dataStoreFactory.createDataStore(new File("D:\\work\\shpdir\\Poi.shp").toURI().toURL());
sds.setCharset(Charset.forName("GBK"));
SimpleFeatureSource featureSource = sds.getFeatureSource();
SimpleFeatureIterator itertor = featureSource.getFeatures().features();
while(itertor.hasNext()) {
SimpleFeature feature = itertor.next();
Iterator it = feature.getProperties().iterator();
while(it.hasNext()) {
Property pro = it.next();
System.out.println(pro);
}
}
itertor.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
GeoTools-10.0-读图形信息
try {
ShpFiles sf = new ShpFiles("D:\\Poi.shp");
ShapefileReader r = new ShapefileReader( sf, false, false, new GeometryFactory() );
while (r.hasNext()) {
Geometry shape = (Geometry) r.nextRecord().shape(); //com.vividsolutions.jts.geom.Geometry;
System.out.println(shape.toString());
}
r.close();
} catch (Exception e) {
e.printStackTrace();
}
GeoTools-10.0-读dbf文件
public void readDBF() {
try {
FileChannel in = new FileInputStream("D:\\Poi.dbf").getChannel();
DbaseFileReader dbfReader = new DbaseFileReader(in, false, Charset.forName("GBK"));
DbaseFileHeader header = dbfReader.getHeader();
int fields = header.getNumFields();
while ( dbfReader.hasNext() ){
DbaseFileReader.Row row = dbfReader.readRow();
// System.out.println(row.toString());
for (int i=0; i
System.out.println(header.getFieldName(i) + " : " + row.read(i));
}
}
dbfReader.close();
in.close();
} catch (Exception e) {
e.printStackTrace();
}
}
GeoTools-10.0-写shape文件
public void write(String filepath) {
try {
//创建shape文件对象
File file = new File(filepath);
Map params = new HashMap();
params.put( ShapefileDataStoreFactory.URLP.key, file.toURI().toURL() );
ShapefileDataStore ds = (ShapefileDataStore) new ShapefileDataStoreFactory().createNewDataStore(params);
//定义图形信息和属性信息
SimpleFeatureTypeBuilder tb = new SimpleFeatureTypeBuilder();
tb.setCRS(DefaultGeographicCRS.WGS84);
tb.setName("shapefile");
tb.add("the_geom", Point.class);
tb.add("POIID", Long.class);
tb.add("NAMEC", String.class);
ds.createSchema(tb.buildFeatureType());
ds.setCharset(Charset.forName("GBK"));
//设置Writer
FeatureWriter writer = ds.getFeatureWriter(ds.getTypeNames()[0], Transaction.AUTO_COMMIT);
//写下一条
SimpleFeature feature = writer.next();
feature.setAttribute("the_geom", new GeometryFactory().createPoint(new Coordinate(116.123, 39.345)));
feature.setAttribute("POIID", 1234567890l);
feature.setAttribute("NAMEC", "某兴趣点1");
feature = writer.next();
feature.setAttribute("the_geom", new GeometryFactory().createPoint(new Coordinate(116.456, 39.678)));
feature.setAttribute("POIID", 1234567891l);
feature.setAttribute("NAMEC", "某兴趣点2");
writer.write();
writer.close();
ds.dispose();
//读取刚写完shape文件的图形信息
ShpFiles shpFiles = new ShpFiles(filepath);
ShapefileReader reader = new ShapefileReader(shpFiles, false, true, new GeometryFactory(), false);
try {
while (reader.hasNext()) {
System.out.println(reader.nextRecord().shape());
}
} finally {
reader.close();
}
} catch (Exception e) { }
}
GeoTools-10.0-由源Shape文件创建新的Shape文件
public void transShape(String srcfilepath, String destfilepath) {
try {
//源shape文件
ShapefileDataStore shapeDS = (ShapefileDataStore) new ShapefileDataStoreFactory().createDataStore(new File(srcfilepath).toURI().toURL());
//创建目标shape文件对象
Map params = new HashMap();
FileDataStoreFactorySpi factory = new ShapefileDataStoreFactory();
params.put(ShapefileDataStoreFactory.URLP.key, new File(destfilepath).toURI().toURL());
ShapefileDataStore ds = (ShapefileDataStore) factory.createNewDataStore(params);
// 设置属性
SimpleFeatureSource fs = shapeDS.getFeatureSource(shapeDS.getTypeNames()[0]);
//下面这行还有其他写法,根据源shape文件的simpleFeatureType可以不用retype,而直接用fs.getSchema设置
ds.createSchema(SimpleFeatureTypeBuilder.retype(fs.getSchema(), DefaultGeographicCRS.WGS84));
//设置writer
FeatureWriter writer = ds.getFeatureWriter(ds.getTypeNames()[0], Transaction.AUTO_COMMIT);
//写记录
SimpleFeatureIterator it = fs.getFeatures().features();
try {
while (it.hasNext()) {
SimpleFeature f = it.next();
SimpleFeature fNew = writer.next();
fNew.setAttributes(f.getAttributes());
writer.write();
}
} finally {
it.close();
}
writer.close();
ds.dispose();
shapeDS.dispose();
} catch (Exception e) { e.printStackTrace(); }
}
java shapefile 中文乱码_GeoTools操作Shape格式文件相关推荐
- java excel 中文乱码_java中读取excel文件中字符串乱码问题解决方法
以前的时候发现直接java读取一个excel文件输出里面的字符串会乱码,中文字符不会乱码,但是遇到英文的时候输出会乱码.这个问题太奇怪了. 我的表格名字为Shirley.xls. 我曾经直接读取exc ...
- Linux下Java程序中文乱码问题研究
Linux下Java程序中文乱码问题研究 摘 要:在一个项目的开发中,我用linux内核源代码和busybox源代码自己编译打造的操作系统mylinux 1.0 ,服务器是我用java语言自己编写的 ...
- java ee 中文乱码的问题
java ee 中文乱码的问题发生中文乱码的三种情况(一) 表单formPost 方法直接在服务器中设置request.setCharacterEncoding("utf-8"); ...
- 记事本TXT中文默认保存的ANSI格式文件乱码,一些软件菜单乱码,右键菜单某些乱码...
记事本TXT中文默认保存的ANSI格式文件乱码,一些软件菜单乱码,右键菜单某些乱码 发现的乱码现象主要体现在WinRAR软件的右键菜单.记事本编辑打开的所有ANSI格式编码的文件.FlashFXP上传 ...
- ArcPy操作shp格式文件
目录 ArcPy操作shp格式文件 shp文件介绍 创建shp 编辑shp 编辑列/字段 插入列 编辑行/记录 主要涉及的对象 arcpy.Cursor(游标)对象 arcpy.Row对象 arcpy ...
- python存成csv文件时中文乱码_Python在向CSV文件写中文时乱码的处理办法
前言 python2最大的坑在于中文编码问题,遇到中文报错首先加u,再各种encode.decode. 当list.tuple.dict里面有中文时,打印出来的是Unicode编码,这个是无解的. 对 ...
- python操作XML格式文件
python操作XML格式文件 python操作XML格式文件 1. 读取文件和内容 2.读取节点数据 3.修改和删除节点 4.构建文档 python操作XML格式文件 可扩展标记语言,是一种简单的数 ...
- python使用 docx 库操作 docx 格式文件
docx 库 文章结构: 一.docx 基本用,创建 docx 文件并添加数据 二.深入理解文本格式(format),并设置所格式属性(attribute) 三.深入理解样式(styles),以及如何 ...
- python操作xlsx格式文件
python操作xlsx格式文件 一.准备工作 二 .xlrd库读取 三.pandas库读取 1.安装pandas: pip install pandas 2.代码如下 3.操作行列 一.准备工作 二 ...
最新文章
- 150亿参数,谷歌开源了史上最大视觉模型V-MoE的全部代码
- Vim 快捷键整理【转】
- Postgresql死锁的处理
- 超多干货!支撑起腾讯公司计费业务的TDSQL(附PPT)
- 【算法与数据结构】堆排序是什么鬼?
- VS2005混合编译ARM汇编代码
- AndroidStudio_安卓原生开发_Android中调用摄像头拍照_并剪裁图片---Android原生开发工作笔记138
- Android 7.1 竖屏转横屏全过程实现-基于高通平台
- java json 反序列化_java-如何将json字符串反序列化为对象
- android ijk 播放器,ijkplayer 播放器:在Android端进行native调试
- R语言入门-安装R和Rstuido软件
- selenium爬取淘宝评论信息
- AUTOSAR关于使用PDUR 进行路由的CDD使用策略
- Docker学习(二)进阶
- Notifiction
- 软件测试工程师的岗位职责
- 基于.NET6的简单三层管理系统
- java我查查_我查查 api
- C语言程序conio,c语言conio.h是什么意思_后端开发
- 机票预订系统(Java)
热门文章
- linux终端快捷方式
- application/x-www-form-urlencoded
- 【转】B树的插入和删除
- 微机原理8086汇编语言上机——Masm环境搭建与常用汇编调试指令
- oracle安装很慢,oracle11g安装后电脑启动很慢怎么解决
- Android 任务栈空间,【Android】任务和返回栈(tasks and back stack)
- java斗地主怎么出牌_斗地主滑动选牌出牌(Cocos Creator)
- python实践项目(二)
- 一招教你在linux服务器配置Jenkins持续集成神器
- ❤️程序员国企太安逸想辞职,又嫌私企大厂压力大996我该如何选择?(高级全栈自动化之路)