Java 下载压缩zip

编程入门 行业动态 更新时间:2024-10-12 03:24:10

<a href=https://www.elefans.com/category/jswz/34/1770091.html style=Java 下载压缩zip"/>

Java 下载压缩zip

相对路径: String mdbDirPath = "./" + "taskPackage";   (当前工程目录同级)     拼路径: String path = mdbDirPath + "\\" + "1报送通知1.mdb";
获取文件流:InputStream inputStream = new FileInputStream(annexFile);

Java压缩zip

 /*** 下载压缩包** @param instId   实例id* @param response 响应* @author 梁伟浩* @date 2023-08-21*/@GetMapping("/downloadZip")@ApiOperation(value = "下载压缩包")@ApiImplicitParam(name = "instId", value = "实例id", required = true, paramType = "query", dataTypeClass = String.class)public void downloadZip(@RequestParam("instId") String instId, HttpServletResponse response) {Asserts.isEmpty(instId, "实例id[instId]不能为空");InputStream inputStream = null;OutputStream outputStream = null;try {businessContentService.zipAttachTree(instId,response);outputStream.flush();} catch (Exception e) {response.setStatus(SC_BAD_REQUEST);try {if (outputStream != null) {response.setCharacterEncoding("utf-8");response.setHeader("Content-Type", "application/json;charset=utf-8");outputStream.write(JSON.toJSONString(R.fail(e.getMessage())).getBytes());}} catch (IOException ex) {throw new RuntimeException(ex);}} finally {try {if (outputStream != null) {outputStream.close();}} catch (IOException ex) {throw new RuntimeException(ex);}try {if (inputStream != null) {inputStream.close();}} catch (IOException ex) {throw new RuntimeException(ex);}}}
 @Overridepublic void zipAttachTree(String instId, HttpServletResponse response) {InstBusinessInfo instBusinessInfo = instBusinessInfoMapper.selectById(instId);String instTitle = instBusinessInfo.getInstTitle();if (instBusinessInfo == null) {throw new BusinessException(instId);}//获取附件树目录BusinessContentRequest instanceContentRequest = new BusinessContentRequest();BusinessContentResponse contentResponse = null;instanceContentRequest.setInstId(instId);instanceContentRequest.setGroupEnum(BusinessContentGroupEnum.DIR_TREE);try {contentResponse = this.getBusinessContent(instanceContentRequest);} catch (Exception e) {e.printStackTrace();}List<BusinessContentVO> contentVOList = contentResponse.getContentVOList();File directory = new File("./" + instTitle);directory.mkdir();//递归创建文件夹并把文件流放进对应文件夹this.getFileName(contentVOList, new StringBuilder(), instTitle);File file = new File("./" + instTitle);File zipFile = null;List<File> souceFileList = new ArrayList();try {souceFileList.add(file);zipFile = new File(instTitle + ".zip");ZipUtil.toZip(zipFile.getName(), souceFileList);BufferedInputStream fis = new BufferedInputStream(new FileInputStream(zipFile));byte[] buffer = new byte[fis.available()];fis.read(buffer);fis.close();// 清空responseresponse.reset();response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(zipFile.getName(), "UTF-8"));OutputStream toClient = new BufferedOutputStream(response.getOutputStream());toClient.write(buffer);toClient.flush();toClient.close();} catch (Exception e) {e.printStackTrace();} finally {//删除本地生成的文件夹与zip压缩包if (file!=null && file.exists()){FileUtil.del(file);}if (zipFile != null && zipFile.exists()) {zipFile.delete();}}}//递归生成文件夹并把流写到对应文件夹public void getFileName(List<BusinessContentVO> contentVOList, StringBuilder sb, String instTitle) {List<StringBuilder> fileNames = new ArrayList<>();for (BusinessContentVO contentVO : contentVOList) {OutputStream outputStream = null;StringBuilder newSb = new StringBuilder(sb); // 创建新的 StringBuilder 对象if (Func.isEmpty(contentVO.getDataId())) {File directory = new File("./" + instTitle + "/" + contentVO.getNodeName());directory.mkdir();newSb.append(contentVO.getNodeName() + "/");} else {String dataId = contentVO.getDataId();InstFileInfo instFileInfo = instFileInfoMapper.selectById(dataId);InputStream inputStream = minioTemplate.getObject(instFileInfo.getFilePath());String fileName = "./" + instTitle + "/" + sb + "/" + contentVO.getNodeName() + "";File outputFile = new File(fileName);try {//把文件夹创建成输出文件outputStream = new FileOutputStream(outputFile);byte[] buffer = new byte[1024];int length;//把文件写到对应的文件夹中while ((length = inputStream.read(buffer)) != -1) {outputStream.write(buffer, 0, length);}inputStream.close();outputStream.close();} catch (Exception e) {e.printStackTrace();}}List<BusinessContentVO> childrenList = contentVO.getChildren();if (childrenList != null) {getFileName(childrenList, newSb, instTitle); // 递归调用时使用新的 StringBuilder 对象}}}

将流写到文件中

 MultipartFile fileInputStream is = file.getInputStream();ZipInputStream zipInputStream = new ZipInputStream(is, Charset.forName("UTF-8"));File jsonFile = new File("./pre/" + zipEntryNameStr);this.writeFile(jsonFile.getAbsolutePath(), zipInputStream);/*** @描述 将流写到文件中* @作者 吕嘉伟* @日期 2023/3/30 17:49*/public void writeFile(String filePath, ZipInputStream zipInputStream) {try (OutputStream outputStream = new FileOutputStream(filePath)) {byte[] bytes = new byte[4096];int len;while ((len = zipInputStream.read(bytes)) != -1) {outputStream.write(bytes, 0, len);}} catch (IOException ex) {System.out.println("解压文件时,写出到文件出错");}}

解析导入的zip压缩包

  /*** @param file* @description: 导入任务包, 更新ss_rwb任务表* @author: 梁伟浩* @date: 2023/10/20 17:08*/@Overridepublic Object importTaskPackage(MultipartFile file) {// 压缩包文件File zipFile = UnZipUtil.getFile(file);//mdb文件路径String path = null;// 压缩包解压到指定位置if (StringUtils.isBlank(taskPackagePath)) {throw new BusinessException("unzip.path.taskPackage 挂载目录路径未配置!");}String id = String.valueOf(IdUtil.getId());String mdbDirPath = taskPackagePath + id;File unzipFile = new File(mdbDirPath);if (!unzipFile.exists()) {unzipFile.mkdirs();}try {//解压zip文件到指定路径文件夹UnZipUtil.unzipFile(zipFile.getPath(), mdbDirPath);// 读取压缩包的内容集合List<UnzipFileVo> unzipList = UnZipUtil.unzip(zipFile);//解析任务包,判断格式是否正常boolean format = false;boolean formatTwo = false;for (UnzipFileVo unzipFileVo : unzipList) {if ("2附件".equals(unzipFileVo.getName())) {format = true;} else {if ("1报送通知.mdb".equals(unzipFileVo.getName())) {formatTwo = true;}}}if (!(format && formatTwo)) {throw new BusinessException("上传的任务包格式有误,请检查任务包!");}//解析附件,上传到minio获取到返回路径,存到ss_rwb数据表
//            String annexPath = mdbDirPath + "\\" + "2附件";String annexPath = mdbDirPath;File folder = new File(annexPath);File[] files = folder.listFiles();//附件数据List<FromFileUploadResponse> annexDatas = new ArrayList<>();if (files != null) {for (File annexFile : files) {if (annexFile.isFile() && !"mdb".equals(FileUtil.getSuffix(annexFile.getName())) && !"json".equals(FileUtil.getSuffix(annexFile.getName()))) {System.out.println(annexFile.getName());//附件上传到minio服务器String objectName = "taskPackage/" + cn.hutool.core.date.DateUtil.year(new Timestamp(System.currentTimeMillis())) + "/" + IdUtil.getId() + "."+ FileUtil.getSuffix(annexFile.getName());//上传文件到minio,返回绝对路径InputStream inputStream = new FileInputStream(annexFile);String paths = fileService.putObject(objectName, inputStream);inputStream.close();InstFileInfo fileInfo = new InstFileInfo();fileInfo.setFileName(annexFile.getName());fileInfo.setFileSize(annexFile.length());fileInfo.setExtension(FileUtil.getSuffix(annexFile.getName()));fileInfo.setStatus(1);//加上存储桶fileInfo.setFilePath("bpm/" + objectName);instFileInfoMapper.insert(fileInfo);FromFileUploadResponse response = new FromFileUploadResponse();response.setFileSize(file.getSize());BeanUtils.copyProperties(fileInfo, response);annexDatas.add(response);//获取存储相对路径String formatLink = fileService.formatLink(paths);}}}//解析mdb文件插入数据path = mdbDirPath + "\\" + "1报送通知.mdb";this.insertRMBData(path, annexDatas);} catch (IOException e) {throw new BusinessException("解析任务包出错!");} finally {//删除本地生成的文件夹与zip压缩包if (unzipFile != null && unzipFile.exists()) {UnZipUtil.deleteFile(unzipFile);}zipFile.delete();}return null;}
  public void insertRMBData(String path, List<FromFileUploadResponse> annexDatas) {Connection connection = AccessUtil.getAccessConnection(path, "", "");try {List<Map<String, Object>> rwbMapList = AccessUtil.select(connection, "XM_SJBSTZB");for (Map<String, Object> map : rwbMapList) {// 将Map对象转换为JSON字符串String jsonString = JSONObject.toJSONString(map);// 使用FastJSON的JSONObject类创建一个新的JSON对象JSONObject jsonObject = JSONObject.parseObject(jsonString);// 将JSON对象转换为SsRwb对象SsRwb ssRwb = jsonObject.toJavaObject(SsRwb.class);UUID uuid = UUID.randomUUID();String uuidString = uuid.toString();ssRwb.setId(uuidString);ssRwb.setCjrXm(jsonObject.get("CJR").toString());ssRwb.setCjSj(new Date());if (annexDatas.size() > 0) {//把附件数据转json数组Gson gson = new Gson();String annexJson = gson.toJson(annexDatas);ssRwb.setFj(annexJson);}ssRwbMapper.insert(ssRwb);}} catch (Exception e) {throw new BusinessException("任务包解析数据插入任务表报错!");} finally {try {connection.close();} catch (SQLException e) {e.printStackTrace();}}}

更多推荐

Java 下载压缩zip

本文发布于:2024-03-14 08:29:49,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1736060.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:Java   zip

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!