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; // 不改變原字符串,如果它不以'/'結尾}