geotools解析.shp.dbf文件工具

文件描述

maven必备jar包 pom.xml

		<dependency>
			<groupId>com.vividsolutions</groupId>
			<artifactId>jts-core</artifactId>
			<version>1.14.0</version>
		</dependency>
		<dependency>
			<groupId>org.geotools</groupId>
			<artifactId>gt-metadata</artifactId>
			<version>${geotools.version}</version>
		</dependency>
		<dependency>
			<groupId>org.geotools</groupId>
			<artifactId>gt-main</artifactId>
			<version>${geotools.version}</version>
		</dependency>
		<dependency>
			<groupId>org.geotools</groupId>
			<artifactId>gt-shapefile</artifactId>
			<version>${geotools.version}</version>
		</dependency>
		<dependency>
			<groupId>org.geotools</groupId>
			<artifactId>gt-api</artifactId>
			<version>${geotools.version}</version>
		</dependency>
		<dependency>
			<groupId>org.geotools</groupId>
			<artifactId>gt-geojson</artifactId>
			<version>${geotools.version}</version>
		</dependency>
		<dependency>
			<groupId>org.geotools</groupId>
			<artifactId>gt-geometry</artifactId>
			<version>${geotools.version}</version>
		</dependency>
		<dependency>
			<groupId>org.geotools</groupId>
			<artifactId>gt-opengis</artifactId>
			<version>${geotools.version}</version>
		</dependency>
		<dependency>
			<groupId>org.geotools</groupId>
			<artifactId>gt-data</artifactId>
			<version>${geotools.version}</version>
		</dependency>
		<dependency>
			<groupId>org.geotools</groupId>
			<artifactId>gt-referencing</artifactId>
			<version>${geotools.version}</version>
		</dependency>
		<!-- https://mvnrepository.com/artifact/com.googlecode.json-simple/json-simple -->
		<dependency>
			<groupId>com.googlecode.json-simple</groupId>
			<artifactId>json-simple</artifactId>
		</dependency>
		<!-- https://mvnrepository.com/artifact/org.jscience/jscience -->
		<dependency>
			<groupId>org.jscience</groupId>
			<artifactId>jscience</artifactId>
			<version>4.3.1</version>
		</dependency>
		
	<!-- https://mvnrepository.com/artifact/com.googlecode.efficient-java-matrix-library/ejml -->
<dependency>
    <groupId>com.googlecode.efficient-java-matrix-library</groupId>
    <artifactId>ejml</artifactId>
    <version>0.25</version>
</dependency>

解析.shp.dbf文件 

package com.kero99.utils;

import java.io.File;
import java.io.StringWriter;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import org.geotools.data.shapefile.ShapefileDataStore;
import org.geotools.data.shapefile.ShapefileDataStoreFactory;
import org.geotools.data.shapefile.dbf.DbaseFileHeader;
import org.geotools.data.shapefile.dbf.DbaseFileReader;
import org.geotools.data.shapefile.files.ShpFiles;
import org.geotools.data.simple.SimpleFeatureCollection;
import org.geotools.data.simple.SimpleFeatureIterator;
import org.geotools.data.simple.SimpleFeatureSource;
import org.geotools.geojson.feature.FeatureJSON;
import org.geotools.geojson.geom.GeometryJSON;
import org.opengis.feature.simple.SimpleFeature;
import org.opengis.feature.type.AttributeDescriptor;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

public class ShapeUtils {
	 /**
	  * 解析.shp 点线面文件
	  * @param path
	  * @return
	  * @throws Exception
	  * @author ygc
	  */
	 public static Map<String, String> ParasShapeFileData(String path) throws Exception {
			Map<String, String> map = new HashMap<String, String>();
			try {

				File file = new File(path);
				String fileName = file.getName();
				ShapefileDataStoreFactory sfdsf = new ShapefileDataStoreFactory();
				ShapefileDataStore sfds = (ShapefileDataStore) sfdsf.createDataStore(file.toURI().toURL());
				
				sfds.setCharset(Charset.forName("GBK"));
				SimpleFeatureSource featureSource = sfds.getFeatureSource();
				
				List<AttributeDescriptor> attrList = sfds.getSchema().getAttributeDescriptors();
				JSONObject pFieldJSON = new JSONObject();
				for (AttributeDescriptor attributeDescriptor : attrList) {
					String pFieldName = attributeDescriptor.getName().toString();
					String pTypeName = attributeDescriptor.getType().getBinding().getSimpleName();
	//				System.out.println(attributeDescriptor.getType().getBinding().getName());
					if (pFieldName == "the_geom") {
						map.put("type", pTypeName);
						pFieldName = "Shape";
						pTypeName = "Geometry";
					}

					pFieldJSON.put(pFieldName, getShapeType(pTypeName));

				}
				// System.out.println(pFieldJSON);
				SimpleFeatureCollection feacollection = featureSource.getFeatures();

				SimpleFeatureIterator iterator = feacollection.features();
				GeometryJSON gjson = new GeometryJSON(15);
				FeatureJSON fjson = new FeatureJSON(gjson);
				
				StringWriter writer = new StringWriter();
				while (iterator.hasNext()) {
					SimpleFeature sFeature = iterator.next();
					if (writer.toString().isEmpty()) {
						fjson.writeFeature(sFeature, writer);
					} else {
						writer.write(',');
						fjson.writeFeature(sFeature, writer);
					}
				}
				iterator.close();
				writer.flush();
				writer.close();
				sfds.dispose();
			  
				String jsonData = "[" + writer.toString() + "]";
				// System.err.println(jsonData);

				JSONObject jsonObject = new JSONObject();
				jsonObject.put("type", "FeatureCollection");
				jsonObject.put("features", JSONArray.fromObject(jsonData));
				map.put("features", jsonObject.toString());
				map.put("fields", pFieldJSON.toString());

				map.put("LayerName", file.getName().replace(".shp", ""));

				map.put("op", "sucess");
	
				// System.out.println(map);
			} catch (Exception e) {
				// TODO: handle exception
				e.printStackTrace();
				map.put("op", "fail");
			}

			return map;
		}
	 	/**
		  * 解析.dbf
		  * @param path
		  * @return
		  * @throws Exception
		  * @author ygc
		  */
	 public static  List<Object> readDbfFile(String path){
		 List<Object> list=new ArrayList<Object>();
		 Map<Object, Object> values = null;
		 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();  
		                values=new LinkedHashMap<Object, Object>();
		                for (int i=0; i<numFields; i++) {  
		                    String title = header.getFieldName(i);  
		                    Object value = entry[i]; 
		                    values.put(title, value);
		                    System.out.println(title+"="+value);  
		                }  
		             
		            } catch (Exception e) {  
		                e.printStackTrace();  
		            }  
		            list.add(values);
		        }  
		    } catch (Exception e) {  
		        e.printStackTrace();  
		    } finally {  
		        if (reader != null) {  
		            //关闭  
		            try {reader.close();} catch (Exception e) {}  
		        }  
		    }
			return list;
	 } 
	 public static String getShapeType(String type) {
			String pDbFieldType = "";
			switch (type) {
			case "Integer":
				pDbFieldType = "INTEGER";
				break;
			case "Double":
				pDbFieldType = "DOUBLE";
				break;
			case "String":
				pDbFieldType = "VARCHAR";
				break;
			case "Date":
				pDbFieldType = "DATETIME";
				break;
			case "Boolean":
				pDbFieldType = "BOOLEAN";
				break;
			case "Geometry":
				pDbFieldType = "Geometry";
				break;
			default:
				pDbFieldType = "TEXT";
				break;
			}
			return pDbFieldType;
		}
	 //投影转换 prj
	 public static void main(String[] args) throws Exception {
		 String path="E:\\shape文件\\设计图斑\\设计图斑-线状\\设计图斑-线状.dbf";
		 ShapeUtils.readDbfFile(path);
		 System.out.println(ShapeUtils.ParasShapeFileData(path));
	}
}
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
可以使用Geotools库来读写shp文件。下面是一个简单的示例代码,可以读取shp文件并打印出其属性表信息: ```java import java.io.File; import java.io.IOException; import org.geotools.data.DataStore; import org.geotools.data.DataStoreFinder; import org.geotools.data.simple.SimpleFeatureCollection; import org.geotools.data.simple.SimpleFeatureIterator; import org.opengis.feature.simple.SimpleFeature; import org.opengis.feature.simple.SimpleFeatureType; public class ShpFileReader { public static void main(String[] args) throws IOException { // 读取shp文件 File file = new File("path/to/shapefile.shp"); DataStore dataStore = DataStoreFinder.getDataStore(file); String typeName = dataStore.getTypeNames()[0]; SimpleFeatureType schema = dataStore.getSchema(typeName); // 获取属性表信息 System.out.println("Feature Type: " + typeName); System.out.println("Number of attributes: " + schema.getAttributeCount()); System.out.println("Attributes: "); for (int i = 0; i < schema.getAttributeCount(); i++) { System.out.println(schema.getAttributeDescriptors().get(i).getName()); } // 获取要素信息 SimpleFeatureCollection collection = dataStore.getFeatureSource(typeName).getFeatures(); try (SimpleFeatureIterator features = collection.features()) { while (features.hasNext()) { SimpleFeature feature = features.next(); System.out.println(feature.getID() + ": " + feature.getDefaultGeometryProperty().getValue()); } } dataStore.dispose(); } } ``` 需要注意的是,需要在pom.xml中添加geotools依赖: ```xml <dependency> <groupId>org.geotools</groupId> <artifactId>gt-shapefile</artifactId> <version>24.0</version> </dependency> ```

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

南归北隐

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值