shp文件解析转换为geojson/wkt格式字符串

此函数用于处理上传的ZIP文件并将其转换为GeoJSON格式的字符串。具体步骤如下:

  1. 验证上传文件是否为ZIP格式。
  2. 创建临时目录以解压ZIP文件。
  3. 解压缩ZIP文件至临时目录。
  4. 查找解压后的.shp文件。
  5. 如果缺少.shx或.dbf辅助文件,则创建空文件。
  6. 读取Shapefile数据。
  7. 将特征集合转换为GeoJSON格式。
  8. 清理临时文件和资源。

函数返回转换后的GeoJSON字符串。

public String shpImport(MultipartFile zipFile) throws IOException {
        // Check if the uploaded file has the .zip extension
        if (!zipFile.getOriginalFilename().toLowerCase().endsWith(".zip")) {
            throw new IllegalArgumentException("Only .zip files are allowed.");
        }

        // Create a temporary directory to extract the ZIP file
        File tempDir = File.createTempFile("shp_upload_", "");
        if (tempDir.exists()) {
            tempDir.delete();
        }
        tempDir.mkdir();

        // Unzip the file to the temporary directory
        try (ZipFile zip = new ZipFile(convertMultipartFileToFile(zipFile))) {
            Enumeration entries = zip.entries();
            while (entries.hasMoreElements()) {
                ZipEntry entry = entries.nextElement();
                File entryDestination = new File(tempDir, entry.getName());
                if (entry.isDirectory()) {
                    entryDestination.mkdirs();
                } else {
                    entryDestination.getParentFile().mkdirs();
                    try (FileOutputStream out = new FileOutputStream(entryDestination)) {
                        FileUtils.copyInputStreamToFile(zip.getInputStream(entry), entryDestination);
                    }
                }
            }
        }

        // Find the .shp file in the extracted files
        File[] shpFiles = tempDir.listFiles((dir, name) -> name.toLowerCase().endsWith(".shp"));
        if (shpFiles == null || shpFiles.length == 0) {
            throw new IllegalArgumentException("The ZIP file does not contain a .shp file.");
        }

        File shpFile = shpFiles[0];
        File shxFile = new File(FilenameUtils.removeExtension(shpFile.getAbsolutePath()) + ".shx");
        File dbfFile = new File(FilenameUtils.removeExtension(shpFile.getAbsolutePath()) + ".dbf");

        // Handle the missing .shx and .dbf files gracefully by creating empty files
        if (!shxFile.exists()) {
            shxFile.createNewFile();
        }
        if (!dbfFile.exists()) {
            dbfFile.createNewFile();
        }

        // Read the shapefile
        FileDataStore store = FileDataStoreFinder.getDataStore(shpFile);
        SimpleFeatureCollection featureCollection = store.getFeatureSource().getFeatures();

        // Convert features to GeoJSON
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        FeatureJSON featureJSON = new FeatureJSON();
        try (FeatureIterator features = featureCollection.features()) {
            featureJSON.writeFeatureCollection(featureCollection, outputStream);
            return outputStream.toString();
        } finally {
            // Clean up temporary files
            store.dispose();
            FileUtils.deleteDirectory(tempDir);
        }
    }

函数返回转换后的WKT字符串。

public String shpImport(MultipartFile zipFile) throws IOException {
        // Check if the uploaded file has the .zip extension
        if (!zipFile.getOriginalFilename().toLowerCase().endsWith(".zip")) {
            throw new IllegalArgumentException("Only .zip files are allowed.");
        }

        // Create a temporary directory to extract the ZIP file
        File tempDir = File.createTempFile("shp_upload_", "");
        if (tempDir.exists()) {
            tempDir.delete();
        }
        tempDir.mkdir();

        // Unzip the file to the temporary directory
        try (ZipFile zip = new ZipFile(convertMultipartFileToFile(zipFile))) {
            Enumeration entries = zip.entries();
            while (entries.hasMoreElements()) {
                ZipEntry entry = entries.nextElement();
                File entryDestination = new File(tempDir, entry.getName());
                if (entry.isDirectory()) {
                    entryDestination.mkdirs();
                } else {
                    entryDestination.getParentFile().mkdirs();
                    try (FileOutputStream out = new FileOutputStream(entryDestination)) {
                        FileUtils.copyInputStreamToFile(zip.getInputStream(entry), entryDestination);
                    }
                }
            }
        }

        // Find the .shp file in the extracted files
        File[] shpFiles = tempDir.listFiles((dir, name) -> name.toLowerCase().endsWith(".shp"));
        if (shpFiles == null || shpFiles.length == 0) {
            throw new IllegalArgumentException("The ZIP file does not contain a .shp file.");
        }

        File shpFile = shpFiles[0];
        File shxFile = new File(FilenameUtils.removeExtension(shpFile.getAbsolutePath()) + ".shx");
        File dbfFile = new File(FilenameUtils.removeExtension(shpFile.getAbsolutePath()) + ".dbf");

        // Handle the missing .shx and .dbf files gracefully by creating empty files
        if (!shxFile.exists()) {
            shxFile.createNewFile();
        }
        if (!dbfFile.exists()) {
            dbfFile.createNewFile();
        }

        // Read the shapefile
        FileDataStore store = FileDataStoreFinder.getDataStore(shpFile);
        SimpleFeatureCollection featureCollection = store.getFeatureSource().getFeatures();

        // Convert features to WKT
        WKTWriter wktWriter = new WKTWriter();
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        try (SimpleFeatureIterator features = featureCollection.features()) {
            while (features.hasNext()) {
                SimpleFeature feature = features.next();
                String wkt = wktWriter.write((Geometry) feature.getDefaultGeometry());
                outputStream.write((wkt + "\n").getBytes());
            }
            return outputStream.toString();
        } finally {
            // Clean up temporary files
            store.dispose();
            FileUtils.deleteDirectory(tempDir);
        }
    }

    private File convertMultipartFileToFile(MultipartFile file) throws IOException {
        File convFile = File.createTempFile("temp", null);
        try (FileOutputStream fos = new FileOutputStream(convFile)) {
            fos.write(file.getBytes());
        }
        return convFile;
    }

所需依赖

        
            org.geotools
            gt-shapefile
            24.1
        
        
            org.geotools
            gt-geojson
            24.1
        
        
            org.geotools
            gt-main
            24.1
        


若依赖下载失败,可在pom文件中添加

        
            osgeo
            osgeo
            https://repo.osgeo.org/repository/release/
        
    

你可能感兴趣的:(前端,数据库,大数据)