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<? extends ZipEntry> 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<? extends ZipEntry> 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;
    }

所需依赖

        <dependency>
            <groupId>org.geotools</groupId>
            <artifactId>gt-shapefile</artifactId>
            <version>24.1</version>
        </dependency>
        <dependency>
            <groupId>org.geotools</groupId>
            <artifactId>gt-geojson</artifactId>
            <version>24.1</version>
        </dependency>
        <dependency>
            <groupId>org.geotools</groupId>
            <artifactId>gt-main</artifactId>
            <version>24.1</version>
        </dependency>


若依赖下载失败,可在pom文件中添加
<repositories>
        <repository>
            <id>osgeo</id>
            <name>osgeo</name>
            <url>https://repo.osgeo.org/repository/release/</url>
        </repository>
    </repositories>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值