基于geotools实现csv转换为shapefile文件。

1、读取CSV文件,将其装入FeatureCollection;

2、利用ShapefileDumper类将FeatureCollection转存到硬盘;

    /*
    * transform CSV to FeatureCollection
    */
1 public void processCSVFile(File csvFile){ ListFeatureCollection collection;
try{
typeName = csvFile.getName().replace(".", "_");
typeName = replaceBlank(typeName);
BufferedReader reader = new BufferedReader(new FileReader(csvFile));
try{
/* First line of the data file is the header */
String line = reader.readLine();
System.out.println("Header: " + line); /*
* We use the DataUtilities class to create a FeatureType that will describe the data in our
* shapefile.
*
* See also the createFeatureType method below for another, more flexible approach.
*/
String[] strArray = line.split("\\,");
int latDex = -1;
int longDex = -1;
List<String> typeSpec = new ArrayList<String>();
typeSpec.add("the_geom:Point:srid="+ SRID); // <- the geometry attribute: Point type
for(int i = 0; i < strArray.length; i ++){
if(strArray[i].contains("Lat")){
latDex = i;
}
else if(strArray[i].contains("Long")){
longDex = i;
}
else{
typeSpec.add(strArray[i] + ":String"); //all String type
}
}
if(CreateCluster)
typeSpec.add("cluster:String"); //add cluster field
String typeSpecs = String.join(",", typeSpec);
final SimpleFeatureType TYPE = DataUtilities.createType(typeName,
typeSpecs // other attribute
);
/*
* GeometryFactory will be used to create the geometry attribute of each feature (a Point
* object for the location)
*/
GeometryFactory geometryFactory = JTSFactoryFinder.getGeometryFactory(null);
SimpleFeatureBuilder featureBuilder = new SimpleFeatureBuilder(TYPE);
/*
* We create a FeatureCollection into which we will put each Feature created from a record
* in the input csv data file
*/
collection = new ListFeatureCollection(TYPE); for (line = reader.readLine(); line != null; line = reader.readLine()) {
if (line.trim().length() > 0) { // skip blank lines
String tokens[] = line.split("\\,");
double latitude = Double.parseDouble(tokens[latDex]);
double longitude = Double.parseDouble(tokens[longDex]); /* Longitude (= x coord) first ! */
Point point = geometryFactory.createPoint(new Coordinate(longitude, latitude)); featureBuilder.add(point);;
for(int i = 0; i < tokens.length; i ++){
if(latDex != i && longDex != i){
String strVal = tokens[i].trim();
featureBuilder.add(strVal);
}
} if(CreateCluster)
featureBuilder.add(""); //add cluster field value
SimpleFeature feature = featureBuilder.buildFeature(null);
collection.add(feature);
}
}
} finally {
reader.close();
}
writeShapeFile(collection); }
catch(Exception ex){
System.out.println(ex.getMessage());
}
}

CSV文件并不包含各字段的类型说明,将经纬度字段转换为Geometry,其他字段都为String类型;

另外,DataUtilities.createType方法创建要素方案时,将所有的String类型的字段长度都设为了java环境下的默认长度254,若字段太多或要素太多会导致shapefile中的dbf文件过大,可参考DataUtilities类,编写自定义类将String类型长度设为自定义长度;

     /*
* FeatureCollection to shapefile
*/
private void writeShapeFile(SimpleFeatureCollection collection){
final File baseDir = resourceLoader.getBaseDirectory();
File shpDir = new File(baseDir.getAbsolutePath() + "/Data/upload");
if(!shpDir.exists()){
shpDir.mkdirs();
}
if(!shpDir.exists())
return; ShapefileDumper dumper = new ShapefileDumper(shpDir);
dumper.setMaxDbfSize(maxDbfSize);
dumper.setMaxShpSize(maxShpSize);
dumper.setCharset(Charset.forName(charSet)); // target charset try {
// if an empty result out of feature type with unknown geometry is created, the
// zip file will be empty and the zip output stream will break
boolean shapefileCreated = false;
shapefileCreated |= dumper.dump(collection); // take care of the case the output is completely empty
if(!shapefileCreated) {
createEmptyWarning(shpDir);
} }
catch(Exception ex){
System.out.println(ex.getMessage());
} } private void createEmptyWarning(File tempDir) throws IOException {
PrintWriter pw = null;
try {
pw = new PrintWriter(new File(tempDir, "README.TXT"));
pw.print("The CSV Upload result is empty, and the geometric type of the features is unknwon:"
+ "an empty point shapefile has been created");
} finally {
pw.close();
}
}

geoserver源码学习与扩展——CSV转shapefile文件的更多相关文章

  1. geoserver源码学习与扩展——自动发布shapefile图层

    geoserver通过工作空间Workspace-数据源DataStore-图层Layer管理地理数据,这些信息都通过Catalog进行组织和管理,要完成自动发布只需要在Catalog中增加相应的信息 ...

  2. geoserver源码学习与扩展——跨域访问配置

    在 geoserver源码学习与扩展——restAPI访问 博客中提到了geoserver的跨域参数设置,本文详细讲一下geoserver的跨域访问配置. geoserver的跨域访问依赖java-p ...

  3. geoserver源码学习与扩展——kml/kmz转shapefile文件

    geoserver通过工作空间Workspace-数据源DataStore-图层Layer管理地理数据,默认只支持shapefile格式的文件发布,不支持kml/kmz.csv的文件格式,所以存在将这 ...

  4. geoserver源码学习与扩展——restAPI访问

    产生这篇文章的想法是在前端通过js调用restAPI时,总是不成功,发送ajax请求时还总是出现类似跨域的问题,后来查找才发现,默认情况下restAPI的访问都需要管理员权限,而通过ajax请求传输用 ...

  5. geoserver源码学习与扩展——增加服务接口

    参看:http://www.cnblogs.com/sillyemperor/archive/2011/01/11/1929420.html 上文写的很详细了.

  6. ddms(基于 Express 的表单管理系统)源码学习

    ddms是基于express的一个表单管理系统,今天抽时间看了下它的代码,其实算不上源码学习,只是对它其中一些小的开发技巧做一些记录,希望以后在项目开发中能够实践下. 数据层封装 模块只对外暴露mod ...

  7. MVC系列——MVC源码学习:打造自己的MVC框架(四:了解神奇的视图引擎)

    前言:通过之前的三篇介绍,我们基本上完成了从请求发出到路由匹配.再到控制器的激活,再到Action的执行这些个过程.今天还是趁热打铁,将我们的View也来完善下,也让整个系列相对完整,博主不希望烂尾. ...

  8. MVC系列——MVC源码学习:打造自己的MVC框架(三:自定义路由规则)

    前言:上篇介绍了下自己的MVC框架前两个版本,经过两天的整理,版本三基本已经完成,今天还是发出来供大家参考和学习.虽然微软的Routing功能已经非常强大,完全没有必要再“重复造轮子”了,但博主还是觉 ...

  9. MVC系列——MVC源码学习:打造自己的MVC框架(一:核心原理)

    前言:最近一段时间在学习MVC源码,说实话,研读源码真是一个痛苦的过程,好多晦涩的语法搞得人晕晕乎乎.这两天算是理解了一小部分,这里先记录下来,也给需要的园友一个参考,奈何博主技术有限,如有理解不妥之 ...

随机推荐

  1. HYSBZ 2160 拉拉队排练(回文树)

    2160: 拉拉队排练 Time Limit: 10 Sec  Memory Limit: 259 MB Submit: 825  Solved: 324 [Submit][Status][Discu ...

  2. Tunneling protocol

    w https://en.wikipedia.org/wiki/Tunneling_protocol

  3. 【推荐】CentOS安装vsftpd-3.0.3+安全配置

    注:以下所有操作均在CentOS 6.5 x86_64位系统下完成. FTP的登录一般有三种方式,分别是: 匿名用户形式:默认安装的情况下,系统只提供匿名用户访问,只需要输入用户anonymous/f ...

  4. Java 集合框架之 JDK 1.5 新特性

    forEach 循环 多用于元素迭代. 适用范围: - 数组 - 实现 Iterable 接口的集合类 格式: for(类型 变量 : Collection 集合 | 数组) { } 传统 for 和 ...

  5. Android之网络----使用HttpClient发送HTTP请求(通过get方法获取数据)

    [正文] 一.HTTP协议初探: HTTP(Hypertext Transfer Protocol)中文 "超文本传输协议",是一种为分布式,合作式,多媒体信息系统服务,面向应用层 ...

  6. Python-selenium 下拉框定位

    1.通过select 进行定位下拉框 首先selenium 很人性化的给提供了一个Select的模块,供处理下来菜单,首先我们需要导入Select,通过from selenium.webdriver. ...

  7. I2C通信

    项目之前研究了I2C通信协议的实现,完成FPGA对视频解码芯片SAA7111A的初始化配置,设计实现了I2C主机对从机(SAA7111A)32个寄存器的写操作,因此只简单实现了I2C的写时序. 这次重 ...

  8. 练T25- focus必看!所有成功截图汇总

    http://www.guokr.com/post/565880/ 25914人加入此小组 发新帖 练T25- focus必看!所有成功截图汇总! 读图模式 作家向威 作家 2014-02-22 07 ...

  9. Django_内置Admin

    Django内置Admin   Django内置的Admin是对于model中对应的数据表进行增删改查提供的组件,使用方式有: 依赖APP: django.contrib.auth django.co ...

  10. python之路——MySQL数据库

    1 MySQL相关概念介绍 MySQL为关系型数据库(Relational Database Management System), 这种所谓的"关系型"可以理解为"表格 ...