引入依赖
<dependency><groupId>org.geotools</groupId><artifactId>gt-shapefile</artifactId><version>${geotools.version}</version></dependency><dependency><groupId>org.geotools</groupId><artifactId>gt-swing</artifactId><version>${geotools.version}</version></dependency>
使用方法
工具类
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.geotools.data.FeatureWriter;
import org.geotools.data.Transaction;
import org.geotools.data.shapefile.ShapefileDataStore;
import org.geotools.data.shapefile.ShapefileDataStoreFactory;
import org.geotools.feature.simple.SimpleFeatureTypeBuilder;
import org.geotools.referencing.crs.DefaultGeographicCRS;
import org.opengis.feature.simple.SimpleFeature;
import org.opengis.feature.simple.SimpleFeatureType;import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;public class ShapeUtil {public static final String DEF_GEOM_KEY = "the_geom";public static final String DEF_ENCODE = "uft-8";public static void createShp(String shpPath, Class<?> geomType, List<Map<String, ?>> data) {try {createShp(shpPath, DEF_ENCODE, geomType, data);} catch (Exception e) {e.printStackTrace();}}public static void createShp(String shpPath, String encode, Class<?> geomType, List<Map<String, ?>> data) {try {if (StringUtils.isEmpty(shpPath)) {throw new Exception("shp文件的路径不能为空,shpPath: " + shpPath);}if (StringUtils.isEmpty(encode)) {throw new Exception("shp文件的编码不能为空,encode: " + encode);}if (Objects.isNull(geomType)) {throw new Exception("shp文件的图形类型不能为空,geomType: " + geomType);}if (CollectionUtils.isEmpty(data)) {throw new Exception("shp文件的图形数据不能为空,data: " + data);}if (!data.get(0).containsKey(DEF_GEOM_KEY)) {throw new Exception("shp文件的图形数据中必须包含the_geom的属性,data: " + data);}File file = new File(shpPath);if (!file.getParentFile().exists()) {file.getParentFile().mkdirs();}Map<String, Serializable> params = new HashMap<>();params.put(ShapefileDataStoreFactory.URLP.key, file.toURI().toURL());ShapefileDataStore ds = (ShapefileDataStore) new ShapefileDataStoreFactory().createNewDataStore(params);ds.createSchema(builderFeatureType(geomType, CollectionUtils.isEmpty(data) ? null : data.get(0)));Charset charset = Charset.forName(encode);ds.setCharset(charset);String[] typeName=ds.getTypeNames();FeatureWriter<SimpleFeatureType, SimpleFeature> writer = ds.getFeatureWriter(ds.getTypeNames()[0], Transaction.AUTO_COMMIT);for (Map<String, ?> map : data) {SimpleFeature feature = writer.next();for (String key : map.keySet()) {if (DEF_GEOM_KEY.equals(key)) {feature.setAttribute(key, map.get(key));} else {feature.setAttribute(key.toUpperCase(), map.get(key));}}}writer.write();writer.close();ds.dispose();} catch (Exception e) {e.printStackTrace();}}public static SimpleFeatureType builderFeatureType(Class<?> geomType, Map<String, ?> data) {SimpleFeatureTypeBuilder ftb = new SimpleFeatureTypeBuilder();ftb.setCRS(DefaultGeographicCRS.WGS84);ftb.setName("shapefile");ftb.add(DEF_GEOM_KEY, geomType);if (MapUtils.isNotEmpty(data)) {for (String key : data.keySet()) {if (Objects.nonNull(data.get(key))) {ftb.add(key.toUpperCase(), data.get(key).getClass());}}}return ftb.buildFeatureType();}public static void zipShapeFile(String shpPath) {try {File shpFile = new File(shpPath);String shpRoot = shpFile.getParentFile().getPath();String shpName = shpFile.getName().substring(0, shpFile.getName().lastIndexOf("."));String zipPath = shpRoot + File.separator + shpName + ".zip";File zipFile = new File(zipPath);InputStream input = null;ZipOutputStream zipOut = new ZipOutputStream(new FileOutputStream(zipFile));zipOut.setComment(shpName);String[] shpFiles = new String[]{shpRoot + File.separator + shpName + ".dbf",shpRoot + File.separator + shpName + ".prj",shpRoot + File.separator + shpName + ".shp",shpRoot + File.separator + shpName + ".shx",shpRoot + File.separator + shpName + ".fix"};for (int i = 0; i < shpFiles.length; i++) {File file = new File(shpFiles[i]);input = new FileInputStream(file);zipOut.putNextEntry(new ZipEntry(file.getName()));int temp = 0;while ((temp = input.read()) != -1) {zipOut.write(temp);}input.close();}zipOut.close();} catch (Exception e) {e.printStackTrace();}}
}
具体使用
public void exportCornerShp(String evid,List<Map<String,String>> cornerDatas, HttpServletResponse httpServletResponse) throws Exception{EvGimcheckTask evGimcheckTask=evGimcheckTaskMapper.selectById(evid);String projectCode=evGimcheckTask.getSubProjectCode();String designCode=evGimcheckTask.getDesignStageCode();String url = "C:\\Users\\admin\\Desktop\\test\\ceshi2222.shp";String str = "LINESTRING (116.21278950384274 39.90557982319698, 116.21177234433465 39.90610963061354, 116.21106912279264 39.90264172209895, 116.21399502548638 39.902612822554126, 116.21629305278306 39.905011479365406, 116.21278950384274 39.90557982319698)";org.locationtech.jts.geom.Geometry geom = WKTUtil.wktToGeom(str);Map<String, Object> m = new HashMap<>();m.put(ShapeUtil.DEF_GEOM_KEY, geom);m.put("name", evGimcheckTask.getGimName());List<Map<String, ?>> data = new ArrayList<>();data.add(m);ShapeUtil.createShp(url, "utf-8", org.locationtech.jts.geom.LineString.class, data);ShapeUtil.zipShapeFile(url);try {String downFile = url.replace(".shp",".zip");java.io.File file = new File(downFile);String filename = file.getName();InputStream fis = new BufferedInputStream(new FileInputStream(file));byte[] buffer = new byte[fis.available()];fis.read(buffer);fis.close();httpServletResponse.reset();httpServletResponse.setContentType("application/x-msdownload");httpServletResponse.setCharacterEncoding("utf-8");httpServletResponse.setHeader("Content-Disposition", "attachment;filename=" + java.net.URLEncoder.encode("ceshi111.zip", "UTF-8"));OutputStream os = new BufferedOutputStream(httpServletResponse.getOutputStream());os.write(buffer);os.flush();os.close();}catch (Exception e){e.printStackTrace();}}
生成文件