springboot解压文件流zip压缩包
原始文件存储的地方:
需要在当前目录下解压该文件,如下图:
代码示例:
private Result<String> getLocationGuideLayerName(YbYstbtqTaskResolveParam params, String fishnetLayerName) throws IOException {// 获取文件(这里的方法是系统的根据文件id获取文件相关的信息)FileDownloadVo fileDownloadVo = uploadService.getFile(params.getFileId());List<AnnexPO> fileInfo = uploadService.getFileInfo(new ArrayList<>(Collections.singletonList(params.getFileId())));if (fileInfo.size() < 1) {throw new RuntimeException("shp文件无效,请重试!");}ZipInputStream zis = new ZipInputStream(fileDownloadVo.getFileStream());ZipEntry zipEntry = zis.getNextEntry();// 文件存储目录+文件名字String filePathTemp = removeLastSlash(uploadConfig.getLocalStorageDirectory()) + fileInfo.get(0).getUploadPath(); // F:\temp\20240708\acbcac4038da45dfa77a3142e9a46501\测试数据2023SAR.zip// 文件存储目录不加文件名String newFilePath = formatFilePath(filePathTemp); // F:\temp\20240708\acbcac4038da45dfa77a3142e9a46501try {// 遍历ZIP文件中的每个条目while (zipEntry != null) {String filePath = newFilePath + File.separator + zipEntry.getName();if (!zipEntry.isDirectory()) {// 提取文件-遍历提取整个zip的所有文件extractFile(zis, filePath);// 关闭当前条目以读取下一个条目zis.closeEntry();}zipEntry = zis.getNextEntry();}// 关闭ZIP输入流zis.close();} catch (IOException e) {throw new RuntimeException("提取shpe文件失败: " + fileDownloadVo.getFileName() + ". 请重试!", e);}}/*** 辅助方法,用于从ZIP输入流中提取文件** @param zis ZIP输入流* @param filePath 文件的完整路径* @throws IOException 如果发生I/O错误*/private void extractFile(ZipInputStream zis, String filePath) throws IOException {BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(filePath));byte[] bytesIn = new byte[4096];int read = 0;while ((read = zis.read(bytesIn)) != -1) {bos.write(bytesIn, 0, read);}bos.close();}/*** @Description: 格式化文件路径,返回文件存储的路径** @Param: [path]* @Return: java.lang.String* @Author yanghaoxing* @Date 2024/7/8 11:27*/public String formatFilePath(String path) {String newPath = path;// 找到最后一个'/'的索引位置int lastIndex = path.lastIndexOf('/');if (lastIndex != -1) { // 确保lastIndexOf找到了'/'newPath = path.substring(0, lastIndex);}return newPath;}/*** @Description: 去掉字符串最后一个 /** @Param: [str]* @Return: java.lang.String* @Author yanghaoxing* @Date 2024/7/8 11:17*/public static String removeLastSlash(String str) {if (str != null && str.endsWith("/")) {return str.substring(0, str.length() - 1);}return str; // 不改变原字符串,如果它不以'/'结尾}