GeoTools应用-DATA

geotools下载地址:http://sourceforge.net/projects/geotools/files/

选择一个版本比如:GeoTools 2.5 Releases,然后下载geotools-2.5.8-src.zip和geotools-2.5.8-bin.zip文件
具体的环境搭建参照:http://hunterlid.iteye.com/blog/698207
Geotools 使用说明

http://docs.codehaus.org/display/GEOTDOC/Home

OpenGIS 软件架构

org.geotools.data
包负责地理数据的读写(如:ShavefileReader用于读取shpfile数据),org.geotools.geometry
包负责提供对JTs的调用接口,以将地理数据封装成JTS中定义的几何对象(Geometry),
org.geotools.feature包负责封装空间几何要素对象(Feature),对应于地图中一个实体,
包含:空间数据(Geometry)、属性数据(Aitribute)、参考坐标系(Refereneedsystem)、
最小外包矩形(EnveloPe)等属性,是Gls操作的核心数据模型。

  1. package com.mapbar.geo.data; 
  2.  
  3. import java.io.File; 
  4. import java.io.IOException; 
  5. import java.io.Serializable; 
  6. import java.net.MalformedURLException; 
  7. import java.nio.charset.Charset; 
  8. import java.util.Collection; 
  9. import java.util.HashMap; 
  10. import java.util.Iterator; 
  11. import java.util.Map; 
  12.  
  13. import org.geotools.data.DataUtilities; 
  14. import org.geotools.data.DefaultTransaction; 
  15. import org.geotools.data.FeatureSource; 
  16. import org.geotools.data.Transaction; 
  17. import org.geotools.data.shapefile.ShapefileDataStore; 
  18. import org.geotools.data.shapefile.ShapefileDataStoreFactory; 
  19. import org.geotools.data.shapefile.ShapefileFeatureLocking; 
  20. import org.geotools.data.shapefile.ShpFiles; 
  21. import org.geotools.data.shapefile.dbf.DbaseFileHeader; 
  22. import org.geotools.data.shapefile.dbf.DbaseFileReader; 
  23. import org.geotools.feature.FeatureCollection; 
  24. import org.geotools.feature.FeatureCollections; 
  25. import org.geotools.feature.FeatureIterator; 
  26. import org.geotools.feature.simple.SimpleFeatureBuilder; 
  27. import org.geotools.referencing.crs.DefaultGeographicCRS; 
  28. import org.opengis.feature.Property; 
  29. import org.opengis.feature.simple.SimpleFeature; 
  30. import org.opengis.feature.simple.SimpleFeatureType; 
  31.  
  32. import com.vividsolutions.jts.geom.Coordinate; 
  33. import com.vividsolutions.jts.geom.GeometryFactory; 
  34. import com.vividsolutions.jts.geom.MultiLineString; 
  35. import com.vividsolutions.jts.geom.Point; 
  36.  
  37. /**
  38. *
  39. * Class MapbarReader.java
  40. *
  41. * Description  Geotools  shp格式文件的读取,创建,和写入操作
  42. *
  43. * Company mapbar
  44. *
  45. * author Chenll E-mail: Chenll@mapbar.com
  46. *
  47. * Version 1.0
  48. *
  49. * Date 2012-2-9 下午03:31:51
  50. */ 
  51. public class MapbarReader { 
  52.  
  53.     /**
  54.      * 读取dbf格式的文件
  55.      *
  56.      * @param path
  57.      */ 
  58.     public void readDBF(String path) { 
  59.         DbaseFileReader reader = null
  60.         try
  61.             reader = new DbaseFileReader(new ShpFiles(path),
    false
  62.                     Charset.forName(“GBK”)); 
  63.             DbaseFileHeader header = reader.getHeader(); 
  64.             int numFields = header.getNumFields(); 
  65.             // 迭代读取记录 
  66.             while (reader.hasNext()) { 
  67.                 try
  68.                     Object[] entry = reader.readEntry(); 
  69.                     for (int i =
    0; i < numFields; i++) { 
  70.                         String title = header.getFieldName(i); 
  71.                         Object value = entry[i]; 
  72.                         String name = title.toString(); 
  73.                         String info = value.toString(); 
  74.                     } 
  75.                 } catch (Exception e) { 
  76.                     e.printStackTrace(); 
  77.                 } 
  78.             } 
  79.         } catch (Exception ex) { 
  80.             ex.printStackTrace(); 
  81.         } finally
  82.             if (reader != null) { 
  83.                 // 关闭 
  84.                 try
  85.                     reader.close(); 
  86.                 } catch (Exception e) { 
  87.                 } 
  88.             } 
  89.         } 
  90.     } 
  91.  
  92.     /**
  93.      * 读取shap格式的文件
  94.      *
  95.      * @param path
  96.      */ 
  97.     public void readSHP(String path) { 
  98.         ShapefileDataStore shpDataStore = null
  99.         try
  100.             shpDataStore = new ShapefileDataStore(new File(path).toURI() 
  101.                     .toURL()); 
  102.             shpDataStore.setStringCharset(Charset.forName(“GBK”)); 
  103.             // 文件名称 
  104.             String typeName = shpDataStore.getTypeNames()[0]; 
  105.             FeatureSource<SimpleFeatureType, SimpleFeature> featureSource =
    null
  106.             featureSource = (FeatureSource<SimpleFeatureType, SimpleFeature>) shpDataStore 
  107.                     .getFeatureSource(typeName); 
  108.             FeatureCollection<SimpleFeatureType, SimpleFeature> result = featureSource 
  109.                     .getFeatures(); 
  110.             FeatureIterator<SimpleFeature> itertor = result.features(); 
  111.             while (itertor.hasNext()) { 
  112.                 SimpleFeature feature = itertor.next(); 
  113.                 Collection<Property> p = feature.getProperties(); 
  114.                 Iterator<Property> it = p.iterator(); 
  115.                 while (it.hasNext()) { 
  116.                     Property pro = it.next(); 
  117.                     // 坐标属性 
  118.                     if (pro.getValue()
    instanceof MultiLineString) { 
  119.                         // 坐标信息 
  120.                         MultiLineString line = (MultiLineString) pro.getValue(); 
  121.                         // 总坐标个数 
  122.                         int pointNums = line.getNumPoints(); 
  123.                         // 中心点坐标 
  124.                         double centX = line.getCentroid().getX(); 
  125.                         double centY = line.getCentroid().getY(); 
  126.  
  127.                     } else
  128.                         // 其它属性以及值 
  129.                         String name = pro.getName().toString(); 
  130.                         String value = pro.getValue().toString(); 
  131.                     } 
  132.                 } 
  133.             } 
  134.             itertor.close(); 
  135.         } catch (MalformedURLException e) { 
  136.             e.printStackTrace(); 
  137.         } catch (IOException e) { 
  138.             e.printStackTrace(); 
  139.         } 
  140.     } 
  141.      
  142.     /**
  143.      * 创建shp文件
  144.      * @param outPath
  145.      */ 
  146.     public void createShp(String outPath) { 
  147.         try
  148.             // 定义属性 
  149.             final SimpleFeatureType TYPE = DataUtilities.createType(“Location”
  150.                     “location:Point,” +
    “NAME:String,” + “INFO:String,” 
  151.                             + “OWNER:String”); 
  152.             FeatureCollection<SimpleFeatureType, SimpleFeature> collection = FeatureCollections 
  153.                     .newCollection(); 
  154.             GeometryFactory geometryFactory = new GeometryFactory(); 
  155.             SimpleFeatureBuilder featureBuilder =
    new
    SimpleFeatureBuilder(TYPE); 
  156.             double latitude = Double.parseDouble(“116.123456789”); 
  157.             double longitude = Double.parseDouble(“39.120001”); 
  158.             String NAME = “运通110路”
  159.             String INFO = “白班车,学生票有效”
  160.             String OWNER = “001”
  161.             // 创建坐标 
  162.             Point point = geometryFactory.createPoint(new Coordinate(longitude, 
  163.                     latitude)); 
  164.             Object[] obj = { point, NAME, INFO, OWNER }; 
  165.             SimpleFeature feature = featureBuilder.buildFeature(null, obj); 
  166.             collection.add(feature); 
  167.             // shap文件的输出路径 
  168.             File newFile = new File(outPath); 
  169.             Map<String, Serializable> params =
    new
    HashMap<String, Serializable>(); 
  170.             params.put(“url”, (Serializable) newFile.toURI().toURL()); 
  171.             params.put(“create spatial index”, (Serializable) Boolean.TRUE); 
  172.             ShapefileDataStoreFactory dataStoreFactory =
    new
    ShapefileDataStoreFactory(); 
  173.             ShapefileDataStore newDataStore = (ShapefileDataStore) dataStoreFactory 
  174.                     .createNewDataStore(params); 
  175.             newDataStore.createSchema(TYPE); 
  176.             newDataStore.setStringCharset(Charset.forName(“GBK”)); 
  177.             newDataStore.forceSchemaCRS(DefaultGeographicCRS.WGS84); 
  178.             String typeName = newDataStore.getTypeNames()[0]; 
  179.             ShapefileFeatureLocking featureSource = (ShapefileFeatureLocking) newDataStore 
  180.                     .getFeatureSource(typeName); 
  181.             // 创建一个事务 
  182.             Transaction transaction = new DefaultTransaction(“create”); 
  183.             featureSource.setTransaction(transaction); 
  184.             try
  185.                 featureSource.addFeatures(collection); 
  186.                 // 提交事务 
  187.                 transaction.commit(); 
  188.             } catch (Exception problem) { 
  189.                 problem.printStackTrace(); 
  190.                 transaction.rollback(); 
  191.             } finally
  192.                 transaction.close(); 
  193.             } 
  194.         } catch (Exception e) { 
  195.             e.printStackTrace(); 
  196.         } 
  197.     } 
  198.  
  199.     public static
    void main(String[] args) { 
  200.         String DBFinput = “D:\\安康公交线_polyline.dbf”
  201.         String shapinput = “D:\\安康公交线_polyline.shp”
  202.         MapbarReader mr = new MapbarReader(); 
  203.         String outShp =  “D:\\busStation.shp”
  204.         mr.createShp(outShp); 
  205.     } 
package com.mapbar.geo.data;

import java.io.File;
import java.io.IOException;
import java.io.Serializable;
import java.net.MalformedURLException;
import java.nio.charset.Charset;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import org.geotools.data.DataUtilities;
import org.geotools.data.DefaultTransaction;
import org.geotools.data.FeatureSource;
import org.geotools.data.Transaction;
import org.geotools.data.shapefile.ShapefileDataStore;
import org.geotools.data.shapefile.ShapefileDataStoreFactory;
import org.geotools.data.shapefile.ShapefileFeatureLocking;
import org.geotools.data.shapefile.ShpFiles;
import org.geotools.data.shapefile.dbf.DbaseFileHeader;
import org.geotools.data.shapefile.dbf.DbaseFileReader;
import org.geotools.feature.FeatureCollection;
import org.geotools.feature.FeatureCollections;
import org.geotools.feature.FeatureIterator;
import org.geotools.feature.simple.SimpleFeatureBuilder;
import org.geotools.referencing.crs.DefaultGeographicCRS;
import org.opengis.feature.Property;
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.MultiLineString;
import com.vividsolutions.jts.geom.Point;

/**
 * 
 * Class MapbarReader.java
 * 
 * Description  Geotools  shp格式文件的读取,创建,和写入操作
 * 
 * Company mapbar
 * 
 * author Chenll E-mail: Chenll@mapbar.com
 * 
 * Version 1.0
 * 
 * Date 2012-2-9 下午03:31:51
 */
public class MapbarReader {

	/**
	 * 读取dbf格式的文件
	 * 
	 * @param path
	 */
	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 < numFields; i++) {
						String title = header.getFieldName(i);
						Object value = entry[i];
						String name = title.toString();
						String info = value.toString();
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		} catch (Exception ex) {
			ex.printStackTrace();
		} finally {
			if (reader != null) {
				// 关闭
				try {
					reader.close();
				} catch (Exception e) {
				}
			}
		}
	}

	/**
	 * 读取shap格式的文件
	 * 
	 * @param path
	 */
	public void readSHP(String path) {
		ShapefileDataStore shpDataStore = null;
		try {
			shpDataStore = new ShapefileDataStore(new File(path).toURI()
					.toURL());
			shpDataStore.setStringCharset(Charset.forName("GBK"));
			// 文件名称
			String typeName = shpDataStore.getTypeNames()[0];
			FeatureSource<SimpleFeatureType, SimpleFeature> featureSource = null;
			featureSource = (FeatureSource<SimpleFeatureType, SimpleFeature>) shpDataStore
					.getFeatureSource(typeName);
			FeatureCollection<SimpleFeatureType, SimpleFeature> result = featureSource
					.getFeatures();
			FeatureIterator<SimpleFeature> itertor = result.features();
			while (itertor.hasNext()) {
				SimpleFeature feature = itertor.next();
				Collection<Property> p = feature.getProperties();
				Iterator<Property> it = p.iterator();
				while (it.hasNext()) {
					Property pro = it.next();
					// 坐标属性
					if (pro.getValue() instanceof MultiLineString) {
						// 坐标信息
						MultiLineString line = (MultiLineString) pro.getValue();
						// 总坐标个数
						int pointNums = line.getNumPoints();
						// 中心点坐标
						double centX = line.getCentroid().getX();
						double centY = line.getCentroid().getY();

					} else {
						// 其它属性以及值
						String name = pro.getName().toString();
						String value = pro.getValue().toString();
					}
				}
			}
			itertor.close();
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 创建shp文件
	 * @param outPath
	 */
	public void createShp(String outPath) {
		try {
			// 定义属性
			final SimpleFeatureType TYPE = DataUtilities.createType("Location",
					"location:Point," + "NAME:String," + "INFO:String,"
							+ "OWNER:String");
			FeatureCollection<SimpleFeatureType, SimpleFeature> collection = FeatureCollections
					.newCollection();
			GeometryFactory geometryFactory = new GeometryFactory();
			SimpleFeatureBuilder featureBuilder = new SimpleFeatureBuilder(TYPE);
			double latitude = Double.parseDouble("116.123456789");
			double longitude = Double.parseDouble("39.120001");
			String NAME = "运通110路";
			String INFO = "白班车,学生票有效";
			String OWNER = "001";
			// 创建坐标
			Point point = geometryFactory.createPoint(new Coordinate(longitude,
					latitude));
			Object[] obj = { point, NAME, INFO, OWNER };
			SimpleFeature feature = featureBuilder.buildFeature(null, obj);
			collection.add(feature);
			// shap文件的输出路径
			File newFile = new File(outPath);
			Map<String, Serializable> params = new HashMap<String, Serializable>();
			params.put("url", (Serializable) newFile.toURI().toURL());
			params.put("create spatial index", (Serializable) Boolean.TRUE);
			ShapefileDataStoreFactory dataStoreFactory = new ShapefileDataStoreFactory();
			ShapefileDataStore newDataStore = (ShapefileDataStore) dataStoreFactory
					.createNewDataStore(params);
			newDataStore.createSchema(TYPE);
			newDataStore.setStringCharset(Charset.forName("GBK"));
			newDataStore.forceSchemaCRS(DefaultGeographicCRS.WGS84);
			String typeName = newDataStore.getTypeNames()[0];
			ShapefileFeatureLocking featureSource = (ShapefileFeatureLocking) newDataStore
					.getFeatureSource(typeName);
			// 创建一个事务
			Transaction transaction = new DefaultTransaction("create");
			featureSource.setTransaction(transaction);
			try {
				featureSource.addFeatures(collection);
				// 提交事务
				transaction.commit();
			} catch (Exception problem) {
				problem.printStackTrace();
				transaction.rollback();
			} finally {
				transaction.close();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public static void main(String[] args) {
		String DBFinput = "D:\\安康公交线_polyline.dbf";
		String shapinput = "D:\\安康公交线_polyline.shp";
		MapbarReader mr = new MapbarReader();
		String outShp =  "D:\\busStation.shp";
		mr.createShp(outShp);
	}
}

org.geotools.data.DataUtilities
a facade classes which can help simplify common data wrangling chores  简化繁琐的通用数据
(1)、定义属性

  1. FeatureType TYPE = DataUtilities.createType(“Location”
  2. “location:Point,” + “NAME:String,” +
    “INFO:String,”+ “OWNER:String”); 
FeatureType TYPE = DataUtilities.createType("Location",
"location:Point," + "NAME:String," + "INFO:String,"+ "OWNER:String");

(2) DataUtilities.schema
You can use this method to quickly get a representation of a FeatureType  返回FeatureType的schema
//返回schema

DataUtilities.spec(featureType))

(3) DataUtilities.collection   Feature数组转换为Feature集合

DataUtilities has helper methods to turn almost anything into a FeatureCollection

  1. Feature[] array;  
  2. …. 
  3. return DataUtilties.collection( array ); 
Feature[] array; 
....
return DataUtilties.collection( array );

(4) DataUtilities.reader 格式化
convert a perfectly good collection to  FeatureReader format.

  1. FeatureCollection collection; 
  2. FeatureReader reader = DataUtilities.reader( collection ); 

转载自:https://blog.csdn.net/sxausgyy/article/details/8113116

You may also like...