Java 读Shapefile
- 格式:doc
- 大小:35.00 KB
- 文档页数:3
shape⽂件的操作⼀、maven依赖引⼊<dependency><groupId>org.geotools</groupId><artifactId>gt-api</artifactId><exclusions><exclusion><groupId>commons-pool</groupId><artifactId>commons-pool</artifactId></exclusion><exclusion><groupId>jgridshift</groupId><artifactId>jgridshift</artifactId></exclusion><exclusion><groupId>Javax.media</groupId><artifactId>jai_core</artifactId></exclusion></exclusions></dependency><dependency><groupId>commons-pool</groupId><artifactId>commons-pool</artifactId></dependency><dependency><groupId>jgridshift</groupId><artifactId>jgridshift</artifactId></dependency><dependency><groupId>Javax.media</groupId><artifactId>jai_core</artifactId></dependency><dependency><groupId>org.geotools</groupId><artifactId>gt-geojson</artifactId></dependency><dependency><groupId>org.geotools</groupId><artifactId>gt-epsg-hsql</artifactId><exclusions><exclusion><groupId>org.hsqldb</groupId><artifactId>hsqldb</artifactId></exclusion></exclusions></dependency><!-- https:///artifact/org.hsqldb/hsqldb --><dependency><groupId>org.hsqldb</groupId><artifactId>hsqldb</artifactId><scope>test</scope></dependency><dependency><groupId>org.geotools</groupId><artifactId>gt-shapefile</artifactId></dependency><dependency><groupId>com.googlecode.json-simple</groupId><artifactId>json-simple</artifactId></dependency>备注:需要配置下载org.geotools的私有仓库<repositories><repository><id>osgeo</id><name>OSGeo Release Repository</name><url>https:///repository/release/</url><snapshots><enabled>false</enabled></snapshots><releases><enabled>true</enabled></releases></repository></repositories>⼆、读取shape⽂件,并转换为对象Tpublic static List<T>readShape(URL url) throws IOException {ShapefileDataStore store = new ShapefileDataStore(url);//设置编码Charset charset = Charset.forName("GBK");store.setCharset(charset);SimpleFeatureSource sfSource = store.getFeatureSource();SimpleFeatureIterator sfIter = sfSource.getFeatures().features();// 从ShapeFile⽂件中遍历每⼀个Feature,然后将Feature转为GeoJSON字符串List<T> list = new ArrayList<>();while (sfIter.hasNext()) {SimpleFeature feature = sfIter.next();// Feature转GeoJSONFeatureJSON fjson = new FeatureJSON();StringWriter writer = new StringWriter();fjson.writeFeature(feature, writer);JSONObject jsonObject = new JSONObject(writer.toString());String type = jsonObject.getStr("type").toLowerCase();if (type.equals("multipolygon")){LOGGER.error("该数据不是图斑:【{}】",writer);continue;}String properties = jsonObject.remove("properties").toString();jsonObject.remove("id");//其他属性T t = JSONUtil.toBean(properties, T.class);if (JudgeUtil.isDBNull(t.getObjectid())){LOGGER.error("该图斑每页objectid:【{}】",writer.toString());continue;}//geojsont.setGeojson(jsonObject.toString());list.add(gisWarnQrstbhhx);}return list;}三、shape⽂件写⼊1、写⼊shape⽂件⼊⼝/*** 写shape⽂件* @param rootFile* @param shapeName shape⽂件名包含后缀名.shp* @param list*/public static void writeShape(File rootFile,String shapeName,List<T>list) throws IOException {if (JudgeUtil.isEmpty(list)){throw new WrongDataException("数据不能为空");}String type = new JSONObject(list.get(0).getGeojson()).getStr("type").toLowerCase();//将list转换为geoJson字符串String geoJson = getGsoJson(list);if (!rootFile.exists() || rootFile.isFile()){rootFile.mkdirs();}File file = new File(rootFile,shapeName);Map<String, Serializable> 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.setDefaultGeometry("the_geom");//添加属性addProperties(type,tb);ds.createSchema(tb.buildFeatureType());//设置编码Charset charset = Charset.forName("GBK");ds.setCharset(charset);FeatureJSON featureJson = new FeatureJSON();SimpleFeatureCollection featureCollection = (SimpleFeatureCollection) featureJson.readFeatureCollection(geoJson);FeatureIterator<SimpleFeature> iterator = featureCollection.features();//设置WriterFeatureWriter<SimpleFeatureType, SimpleFeature> writer = ds.getFeatureWriter(ds.getTypeNames()[0], Transaction.AUTO_COMMIT);//写下⼀条SimpleFeature srcFeature;Iterator<Property> properties;while (iterator.hasNext()){srcFeature = iterator.next();properties = srcFeature.getProperties().iterator();SimpleFeature destFeature = writer.next();while (properties.hasNext()){Name name = properties.next().getName();Object attribute = srcFeature.getAttribute(name);if (!(attribute instanceof Geometry)){destFeature.setAttribute(name, attribute);}}destFeature.setDefaultGeometryProperty(srcFeature.getDefaultGeometryProperty());}writer.write();writer.close();ds.dispose();}2、将List<T>转换为geojson/*** T转geojson* @param list* @return*/private static String getGsoJson(List<T>list){JSONObject jsonObject = new JSONObject();jsonObject.putOnce("type","FeatureCollection");JSONArray jsonArray = new JSONArray();jsonObject.putOnce("features",jsonArray);for (T t : list) {JSONObject feature = new JSONObject();feature.putOnce("type","Feature");feature.putOnce("geometry",new JSONObject(t.getGeojson()));t.setGeojson(null);t.setGeom(null);t.setGid(null);feature.putOnce("properties",JSONUtil.parseObj(t));jsonArray.add(feature);}return jsonObject.toString();}3、通过反射添加properties/*** 通过反射添加properties* @param tb*/private static void addProperties(String type, SimpleFeatureTypeBuilder tb){Field[] declaredFields = T.class.getDeclaredFields();setType(tb,type.toLowerCase());for (Field declaredField : declaredFields) {String name = declaredField.getName();if (!name.equals("serialVersionUID") && !name.equals("geojson") && !name.equals("geom")){ tb.add(name,declaredField.getType());}}}4、设置类型private static void setType(SimpleFeatureTypeBuilder tb,String type){if (type.equals("point")) {tb.add("the_geom", Point.class);} else if (type.equals("line")) {tb.add("the_geom", LineString.class);} else if (type.equals("polygon")) {tb.add("the_geom", Polygon.class);} else if (type.equals("multipoint")) {tb.add("the_geom", MultiPoint.class);} else if (type.equals("multiline")) {tb.add("the_geom", MultiLineString.class);} else if (type.equals("multipolygon")) {tb.add("the_geom", MultiPolygon.class);}}。
浅谈java中⽂件的读取File、以及相对路径的问题⼀、对于java项⽬中⽂件的读取1、使⽤System 或是系统的Properties对象①直接是使⽤ String relativelyPath=System.getProperty("user.dir");②使⽤Properties对象我们先来遍历⼀下系统的属性:Properties properties = System.getProperties();Enumeration pnames = properties.propertyNames();while (pnames.hasMoreElements()) {String pname = (String) pnames.nextElement();System.out.print(pname + "--------------");System.out.println(properties.getProperty(pname));}这是系统的属性,由此其实还是绕到使⽤ user.dir 属性来取得当前项⽬的真是路径通过 String relativelyPath = properties.getProperty("user.dir"); 取得我⾃⼰的电脑上⾯的项⽬ Log4jProj 的真是路径是:user.dir--------------D:\Develop\workspace\ws_self\10_ws_eclipse_j2ee_mars\Log4jProj其实⽅式①和⽅式②⼀个意思,殊途同归2、第⼆种⽅式:使⽤当前类的类加载器进⾏获取 ClassLoader⾸先来回顾⼀下,如何获取Class字节码实例,三种⽅式:(⽐如我的类叫Demo)① Demo.class② Class.forName("类的全称")③利⽤Demo的实例对象,调⽤对象的getClass()⽅法获取该对象的Class实例回顾了如何获取Class字节码实例之后,然后再来回顾⼀下,如何获取ClassLoader对象① Demo.class.getClassLoader()② Class.forName("类的全称").getClassLoader()③假设demo为Demo的实例化对象 demo.getClass().getClassLoader()④通过Thread对象的getContextClassLoader() ⽅法来获取Thread.currentThread().getContextClassLoader()进⼊正题:有了ClassLoader对象之后,我们这么时候通过ClassLoader对象来获取java项⽬中的⽂件⾸先让⼤家看下我当前的项⽬⽬录结构以及实际⽂件的⽬录结构需求就是,此时Test需要读取 log4j.properties ⽂件的路径⽤到ClassLoader的两个⽅法,⼀个是静态的⼀个⾮静态的输出结果:记住哦,这⾥的getSystemResource⽅法获取的是URL对象,需要调⽤getPath()⽅法获取路径1、当只是获取 log4j.properties ⽂件输⼊流的时候可以通过以下两种⽅式①依然是使⽤ ClassLoader, 其中有两个⽅法,两者⼀个是静态⼀个⾮静态ClassLoader.getSystemResourceAsStream("config/log4j.properties");Thread.currentThread().getContextClassLoader().getResourceAsStream("config/log4j.properties");②先通过File⽂件包装之后,然后新建⼀个输⼊流File file01 = new File("config/log4j.properties");System.out.println(file01.getAbsolutePath());File file02 = new File(properties.getProperty("user.dir") + "/bin/config/log4j.properties");System.out.println(file02.getAbsolutePath());//ClassLoader.getSystemResource获取的是URL对象File file03 = new File(ClassLoader.getSystemResource("config/log4j.properties").getPath());System.out.println(file03.getAbsolutePath());其中创建file03 的⽅式不建议采纳,因为getSystemResource⽅法如果没获取到⽂件,则得到的URL对象为null,此时再调⽤getPath()就会报错如果有了⽂件对象就可以直接创建流了,此处不作赘述以上这篇浅谈java 中⽂件的读取File、以及相对路径的问题就是⼩编分享给⼤家的全部内容了,希望能给⼤家⼀个参考,也希望⼤家多多⽀持。
Java使⽤GDAL读写shapefile 读取shp⽂件,并把它转化为jsonimport org.gdal.ogr.*;import org.gdal.ogr.Driver;import org.gdal.gdal.*;public class GdalShpTest {public static void main(String[] args) {// 注册所有的驱动ogr.RegisterAll();// 为了⽀持中⽂路径,请添加下⾯这句代码gdal.SetConfigOption("GDAL_FILENAME_IS_UTF8","YES");// 为了使属性表字段⽀持中⽂,请添加下⾯这句gdal.SetConfigOption("SHAPE_ENCODING","");String strVectorFile = "D:\\test\\NODE.shp";//打开⽂件DataSource ds = ogr.Open(strVectorFile,0);if (ds == null){System.out.println("打开⽂件失败!" );return;}System.out.println("打开⽂件成功!" );Driver dv = ogr.GetDriverByName("GeoJSON");if (dv == null){System.out.println("打开驱动失败!" );return;}System.out.println("打开驱动成功!" );dv.CopyDataSource(ds, "D:\\test\\node.json");System.out.println("转换成功!" );}}写shp⽂件import org.gdal.ogr.*;import org.gdal.gdal.*;class writeShp2 {public static void main(String[] args) {writeShp2 readshpObj = new writeShp2();readshpObj.WriteVectorFile();}static void WriteVectorFile() {String strVectorFile = "D:\\test\\test.shp";ogr.RegisterAll();gdal.SetConfigOption("GDAL_FILENAME_IS_UTF8", "NO");gdal.SetConfigOption("SHAPE_ENCODING", "CP936");String strDriverName = "ESRI Shapefile";org.gdal.ogr.Driver oDriver = ogr.GetDriverByName(strDriverName);if (oDriver == null) {System.out.println(strVectorFile + " 驱动不可⽤!\n");return;}DataSource oDS = oDriver.CreateDataSource(strVectorFile, null);if (oDS == null) {System.out.println("创建⽮量⽂件【" + strVectorFile + "】失败!\n");return;}Layer oLayer = oDS.CreateLayer("TestPolygon", null, ogr.wkbPolygon, null);if (oLayer == null) {System.out.println("图层创建失败!\n");return;}// 下⾯创建属性表// 先创建⼀个叫FieldID的整型属性FieldDefn oFieldID = new FieldDefn("FieldID", ogr.OFTInteger);oLayer.CreateField(oFieldID);// 再创建⼀个叫FeatureName的字符型属性,字符长度为50FieldDefn oFieldName = new FieldDefn("FieldName", ogr.OFTString);oFieldName.SetWidth(100);oLayer.CreateField(oFieldName);FeatureDefn oDefn = oLayer.GetLayerDefn();// 创建三⾓形要素Feature oFeatureTriangle = new Feature(oDefn);oFeatureTriangle.SetField(0, 0);oFeatureTriangle.SetField(1, "三⾓形");Geometry geomTriangle = Geometry.CreateFromWkt("POLYGON ((0 0,20 0,10 15,0 0))");oFeatureTriangle.SetGeometry(geomTriangle);oLayer.CreateFeature(oFeatureTriangle);// 创建矩形要素Feature oFeatureRectangle = new Feature(oDefn);oFeatureRectangle.SetField(0, 1);oFeatureRectangle.SetField(1, "矩形");Geometry geomRectangle = Geometry.CreateFromWkt("POLYGON ((30 0,60 0,60 30,30 30,30 0))");oFeatureRectangle.SetGeometry(geomRectangle);oLayer.CreateFeature(oFeatureRectangle);// 创建五⾓形要素Feature oFeaturePentagon = new Feature(oDefn);oFeaturePentagon.SetField(0, 2);oFeaturePentagon.SetField(1, "五⾓形");Geometry geomPentagon = Geometry.CreateFromWkt("POLYGON ((70 0,85 0,90 15,80 30,65 15,70 0))"); oFeaturePentagon.SetGeometry(geomPentagon);oLayer.CreateFeature(oFeaturePentagon);oDS.SyncToDisk();System.out.println("\n数据集创建完成!\n");}}得到test.dbf, test.shp, test.shx。
geotools 使用Geotools是一个开源的Java库,用于处理和分析地理空间数据。
它提供了许多工具和算法,使得开发人员能够轻松地读取、写入和操作各种地理空间数据格式。
例如,它支持处理矢量数据、栅格数据、网格数据等。
本文将介绍如何使用 Geotools 库来处理地理空间数据。
1. 安装 Geotools使用 Geotools 库需要先下载并安装它。
可以从 Geotools 的官方网站上下载最新版本的 Geotools。
下载完成后,将其解压缩到本地文件夹中。
2. 创建一个 Geotools 工程在 Eclipse 中创建一个新的 Java 项目。
右键单击项目,选择Build Path 和 Configure Build Path。
在 Libraries 标签下点击Add External JARs,选择 Geotools 库的所有 JAR 文件,将它们添加到项目中。
3. 读取地理空间数据使用 Geotools 库可以轻松读取各种地理空间数据格式,例如Shapefile 文件、GeoJSON 文件、KML 文件等。
以下是一个示例代码,用于读取 Shapefile 文件:```File file = new File('path/to/shapefile.shp');Map<String, Object> connect = new HashMap<String, Object>();connect.put('url', file.toURI().toURL());DataStore dataStore =DataStoreFinder.getDataStore(connect);String[] typeNames = dataStore.getTypeNames();String typeName = typeNames[0];SimpleFeatureSource featureSource =dataStore.getFeatureSource(typeName);SimpleFeatureCollection collection =featureSource.getFeatures();try (SimpleFeatureIterator features =collection.features()) {while (features.hasNext()) {SimpleFeature feature = features.next();System.out.println(feature.getID() + ': ' +feature.getAttribute('NAME'));}}```4. 分析地理空间数据Geotools 库提供了许多分析地理空间数据的功能,例如空间查询、空间缓冲区分析、空间交叉分析等。
geotools的java方法使用GeoTools的Java方法进行地理空间数据处理地理空间数据处理是地理信息系统(GIS)中的一个重要环节,它涉及到地理数据的获取、存储、分析和可视化等方面。
GeoTools是一个使用Java语言开发的开源GIS工具包,它提供了丰富的API和功能,可以帮助开发者进行地理空间数据处理。
1. 创建空间数据模型在GeoTools中,空间数据模型是通过Feature、Geometry和Attribute三个核心接口来表示的。
Feature表示地理要素,Geometry表示几何形状,Attribute表示属性信息。
我们可以使用这些接口来创建空间数据模型,并进行操作。
2. 读取和写入地理数据GeoTools提供了多种方式来读取和写入地理数据,包括读取和写入Shapefile、GeoPackage、PostGIS等格式的数据。
通过使用相应的数据源和数据存储对象,我们可以轻松地将地理数据加载到内存中,并对其进行处理和分析。
3. 空间数据查询和过滤GeoTools提供了丰富的查询和过滤功能,可以根据空间关系、属性条件等进行数据查询和过滤。
我们可以使用Filter接口来定义查询和过滤条件,并使用DataStore的query方法来执行查询操作。
4. 空间数据分析GeoTools提供了多种空间数据分析算法,包括缓冲区分析、叠加分析、空间插值等。
我们可以使用相应的工具类和方法来执行这些分析操作,并获取结果。
5. 地图绘制和可视化GeoTools提供了强大的地图绘制和可视化功能,可以将地理数据以图形的方式展示出来。
我们可以使用MapFrame、MapPane等类来创建地图窗口,并通过设置样式、渲染器等属性来实现地图的绘制和可视化。
6. 地理空间数据的转换和投影在地理空间数据处理过程中,经常需要进行数据转换和投影操作。
GeoTools提供了丰富的转换和投影工具,可以帮助我们将地理数据从一种坐标系转换到另一种坐标系,并进行投影变换。
java读取文件内容的方法在Java编程中,读取文件是一个常见的操作,可以利用Java提供的各种类和方法来实现。
下面介绍几种常用的方法:1. 使用BufferedReader类读取文件内容:```try {FileReader fileReader = new FileReader("文件路径");BufferedReader bufferedReader = new BufferedReader(fileReader);String line;while ((line = bufferedReader.readLine()) != null) {// 处理每一行的内容System.out.println(line);}bufferedReader.close();} catch (IOException e) {e.printStackTrace();}```以上代码首先打开一个文件,然后使用BufferedReader类逐行读取文件内容,当读取到的行为null时表示已经读取完整个文件。
2. 使用Scanner类读取文件内容:```try {File file = new File("文件路径");Scanner scanner = new Scanner(file);while (scanner.hasNextLine()) {String line = scanner.nextLine();// 处理每一行的内容System.out.println(line);}scanner.close();} catch (FileNotFoundException e) {e.printStackTrace();}```上述代码利用Scanner类可以方便地按行读取文件内容,同样当读取到的行为null时表示已经读取完整个文件。
3. 使用Files类读取文件内容:```try {List<String> lines = Files.readAllLines(Paths.get("文件路径"));for (String line : lines) {// 处理每一行的内容System.out.println(line);}} catch (IOException e) {e.printStackTrace();}```上述代码使用Files类的readAllLines方法一次性读取文件的所有行,返回一个包含所有行内容的列表。
数据的天空?如何用IDL处理Shapefile数据Bloged in IDL编程作者: wulizong 星期四 07月 16, 2009遥感和GIS不分家,IDL擅长处理遥感数据,但偶尔也需要用来处理一些GIS数据,不过还好IDL能处理Shapefile数据。
使用IDL处理shapefile格式,需要了解IDLffShape对象,IDL帮助中有一些说明和代码,但过于简单,不熟悉的人很难上手,现对几个关键点进行说明:一、读取shapefile文件1.首先要打开文件我们用Arcview带的数据做例子吧,就用那个国界数据吧。
创建和销毁idlffshape分别使用的是IDL处理对象的通用命令OBJ_new和Obj_Destroy,每建立一个对象都要记着要销毁,否则会出现内存不足问题。
pro readshapefileshapefile='C:\ESRI\ESRIDATA\WORLD\country.shp' ;定义shape文件位置oshp=Obj_New('IDLffShape',filename)print oshp;中间处理代码Obj_destroy,oshp ;销毁一个shape对象end如果读取错误,oshp会返回-1,否则得话返回的就是一个结构体。
2.获取整体描述信息读完shape对象后,就需要读几何数据和属性表数据了。
Shapefile数据由几何体(或实体Entity)和属性表两部分组成,而几何体一般又包括点(point)、线(polyline)和多边形(polygon)(当然也有其它类型,但不常用)。
属性表包括属性表结构、字段个数和记录个数,属性表记录数与实地必须一一对应,属性表的结构又包含字段名,字段类型,字段长度和精确度。
在IDL读取数据前,需要了解一些全局属性,知道有多少个几何体和记录,属性表中有多少个字段,就需要用GetProperty方法,它查询shape文件的属性,包括实体类型,实体个数,属性表结构,属性表字段个数,记录数等,代码如下:pro readshapefileshapefile='C:\ESRI\ESRIDATA\WORLD\country.shp' ;定义shape文件位置oshp=Obj_New('IDLffShape',filename)oshp->getproperty,n_entities=n_ent,Attribute_info=attr_inf o,n_attributes=n_attr,Entity_type=ent_typeprint,'实体个数:'n_entprint,'属性表字段数:',n_attrprint,'实体类型代码:',ent_typeObj_destroy,oshp ;销毁一个shape对象end3.再了解几个概念•bouns存储的是每个实体的范围,是一个有8个元素的数组([x0,x1,x2,x3,x4,x5,x6,x7]),其中x0 —最小x值,x1 —最小y值,x2最小z值(高度),x3 —最小M值(测量值,一般不用)x4-x7就是最大值了。
shapefile包的用法-回复Shapefile是一种经常被使用的地理信息系统(GIS)文件格式,它可以用来存储和传输地理位置、空间对象和属性信息。
它由几个文件组成,包括.shp、.shx、.dbf和.prj文件。
这篇文章将一步一步地介绍如何使用shapefile包来读取、创建和编辑shapefile文件。
第一步:安装shapefile包首先,在Python环境中安装shapefile包。
可以使用以下命令在终端或命令提示符中安装:pip install pyshp安装完成后,你就可以在Python程序中使用shapefile包了。
第二步:导入shapefile包在Python程序的开头,导入shapefile包:pythonimport shapefile第三步:读取shapefile文件使用以下代码来读取一个shapefile文件:pythonsf = shapefile.Reader("path/to/shapefile.shp")这将创建一个`ShapefileReader`对象,用于读取shapefile文件的几何形状、属性以及其他相关信息。
第四步:访问shapefile的几何对象和属性可以使用以下代码来访问shapefile中的几何对象和属性:pythonshapes = sf.shapes() # 获取所有几何形状records = sf.records() # 获取所有属性记录通过迭代遍历这些几何形状和属性记录,可以获取每个几何形状的坐标和每个属性记录的值:pythonfor shape in shapes:points = shape.points # 获取几何形状的坐标列表# 处理坐标数据...for record in records:attributes = record.attributes # 获取属性记录的值# 处理属性数据...第五步:创建shapefile文件shapefile包还允许创建新的shapefile文件并添加几何对象和属性。
geotools的java方法使用Geotools进行空间数据处理的Java方法Geotools是一个开源的Java库,提供了一系列用于处理地理空间数据的方法和工具。
它包含了许多功能强大的类和方法,可以帮助开发者进行地图制作、空间数据分析、地理信息系统开发等工作。
本文将介绍一些常用的Geotools的Java方法,以帮助读者更好地了解和使用这个库。
1. 空间数据读取和写入使用Geotools可以方便地读取和写入各种地理空间数据格式,如Shapefile、GeoJSON、KML等。
通过使用FeatureSource类和FeatureStore类,可以轻松地读取和写入空间数据。
例如,可以使用DataStore类读取一个Shapefile,并通过FeatureCollection 获取其中的要素集合。
2. 空间数据过滤Geotools提供了丰富的空间数据过滤方法,可以根据空间关系、属性条件等对空间数据进行筛选和查询。
通过使用Filter类和CQL (Common Query Language)表达式,可以轻松地实现各种空间数据的过滤操作。
例如,可以使用FilterFactory类创建一个SpatialFilter对象,通过设置空间关系和几何对象,对空间数据进行空间关系的过滤。
3. 空间数据转换Geotools提供了许多方法用于空间数据的转换,可以将一个格式的空间数据转换为另一个格式。
例如,可以使用DataUtilities类将一个FeatureCollection对象转换为GeoJSON格式的字符串,或将一个GeoJSON格式的字符串转换为FeatureCollection对象。
4. 空间数据分析Geotools提供了一些常用的空间数据分析方法,如缓冲区分析、叠加分析、空间插值等。
通过使用相应的类和方法,可以方便地实现这些空间数据分析操作。
例如,可以使用BufferOp类对一个几何对象进行缓冲区分析,或使用OverlayOp类对两个几何对象进行叠加分析。
geotools 叠加geotiff与shapefile -回复如何使用Geotools工具包来叠加Geotiff与Shapefile。
Geotools是一个开源的Java库,用于处理和分析地理空间数据。
它提供了一系列功能强大的工具,可以用来读取、处理和分析各种地理空间数据格式。
在本文中,我们将使用Geotools来叠加Geotiff和Shapefile文件,以便分析和展示地理空间数据。
第一步:准备数据在开始之前,我们需要准备一些数据。
首先,我们需要一个Geotiff文件和一个Shapefile文件。
Geotiff文件是一种常见的栅格地理空间数据格式,可以包含高程、影像等信息。
Shapefile文件是一种矢量地理空间数据格式,可以包含点、线、面等几何要素。
假设我们有一个名为"elevation.tif"的Geotiff文件和一个名为"points.shp"的Shapefile文件。
"elevation.tif"文件包含了一个区域的高程数据,"points.shp"文件包含了一些点要素。
第二步:创建工程打开你喜欢的Java开发环境(比如Eclipse),创建一个新的Java工程。
然后,将Geotools库添加到你的工程中。
你可以从Geotools官方网站下载最新版本的库文件,并添加到你的工程的类路径下。
第三步:导入必要的类在你的Java代码中,导入必要的Geotools类。
在我们的例子中,我们将需要导入以下几个类:import org.geotools.data.FileDataStore;import org.geotools.data.FileDataStoreFinder;import org.geotools.data.simple.SimpleFeatureCollection;import org.geotools.data.simple.SimpleFeatureIterator;import org.geotools.feature.DefaultFeatureCollection;import org.opengis.feature.simple.SimpleFeature;import org.opengis.feature.simple.SimpleFeatureType;import org.opengis.geometry.BoundingBox;第四步:读取Geotiff文件使用Geotools提供的类来读取Geotiff文件。
Java 读Shapefile
package data;
import geometry.Point;
import geometry.Polyline;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import util.Convert;
public class PolylineShape {
@SuppressWarnings("unused")
private final int type = 3;
private String fileName;
private ArrayList<Polyline> list;
private double xMin;
private double yMin;
private double xMax;
private double yMax;
private byte[] read4(FileInputStream input) { byte[] b = new byte[4];
for(int i = 0; i < 4; i++) {
try {
b[i] = (byte)input.read();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return b;
}
private int read4Big(FileInputStream input) { return Convert.bytesToIntBig(read4(input));
}
private int read4Little(FileInputStream input) { return Convert.bytesToIntLittle(read4(input));
}
private double read8(FileInputStream input) { byte[] b = new byte[8];
for(int i = 0; i < 8; i++) {
try {
b[i] = (byte)input.read();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return Convert.bytesToDouble(b);
}
private void read() throws Exception
{
File file = new File(fileName);
FileInputStream input = new FileInputStream(file);
int index = 0;
while(input.available() > 0) {
input.read();
index++;
if(index == 36)
break;
}
xMin = this.read8(input);
yMin = this.read8(input);
xMax = this.read8(input);
yMax = this.read8(input);
index += 32;
while(input.available() > 0) {
input.read();
index++;
if(index == 100)
break;
}
while(input.available() > 0) {
list.add(this.readPolyline(input));
}
System.out.println(input.available());
}
private Polyline readPolyline(FileInputStream input) { int id = this.read4Big(input);
read4Big(input);//记录长度
read4Little(input);//几何类型
double[] box = new double[4];
box[0] = read8(input);
box[1] = read8(input);
box[2] = read8(input);
box[3] = read8(input);
int numParts = read4Little(input);
int numPoints = read4Little(input);
int[] parts = new int[numParts];
for(int i = 0; i < numParts; i++)
parts[i] = read4Little(input);
Point[] points = new Point[numPoints];
for(int i = 0; i < numPoints; i++) {
points[i] = new Point();
points[i].setX(read8(input));
points[i].setY(read8(input));
}
Polyline line = new Polyline(id, box, parts, points);
return line;
// TODO Auto-generated method stub
}
PolylineShape(String fileName) throws Exception { this.fileName = fileName;
list = new ArrayList<Polyline>();
read();
}
/**
* @param args
* @throws Exception
*/
public static void main(String[] args) throws Exception { // TODO Auto-generated method stub
new PolylineShape("complexshp.shp");
}
}。