java 选程获取文件并下载 写文件 下载

  1. 测试
   @Test
    public void test04() throws Exception {
        // 测试url
        String httpUrl = "https://xxx/rest/file-system/operation/download?fileKey=$17753fba-7251-47cf-a955-f748b4ff4d8e$2927923069&signature=Q9MNzH%2B594jZEC76GFDhnTWgr5k%3D%0A&expire=1669356887399&type=pdf&fileName=%E5%B9%B3%E5%8F%B0%E7%BB%B4%E5%BA%A6%E5%AF%B9%E8%B4%A6%E5%8D%95";
        String httpUrl1 = "https://xxx/rest/file-system/operation/download?fileKey=$55d7e9fd-3287-4499-9d9e-5cd52f593e4f$3236802050&signature=TTH1A8hWiX7g6gnh2OYRTOkRjzk%3D%0A&expire=1669292158061&type=file&fileName=%E5%B9%B3%E5%8F%B0%E7%BB%B4%E5%BA%A6%E5%AF%B9%E8%B4%A6%E5%8D%951";
        List<String> strings = new ArrayList<>();
        strings.add(httpUrl);
        strings.add(httpUrl1);
        List<Map<String, Object>> maps = getRomteFileData(strings);
        downloadZip(maps);
    }
  1. 远程文件获取组装到map中
public List<Map<String, Object>> getRomteFileData(List<String> httpUrls) throws IOException {
        String strTime = DateUtil.format(new Date(), "yyyyMMddHHmmss");
        // 待下载文件列表
        List<Map<String, Object>> files = new ArrayList<>();
        // 排除重名文件
        Set<String> existFileName = new HashSet<>();
        for (String httpUrl : httpUrls) {
            String fileName = null;
            Map<String, Object> map = new HashMap<>();
            InputStream inputStream = null;
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            try {
                URL url = new URL(httpUrl);
                // 获取中文文件名
                String fileNameEncode = org.apache.commons.lang3.StringUtils.substringAfter(url.getFile(), "&fileName=");
                fileName = URLDecoder.decode(fileNameEncode, CharsetUtil.UTF_8);
                if (!existFileName.add(fileName)) {
                    continue;
                }
                map.put("fileName", strTime + fileName + ".pdf");

                HttpURLConnection con = (HttpURLConnection) url.openConnection();
                con.setRequestMethod("GET");
                con.setConnectTimeout(10 * 1000);
                inputStream = con.getInputStream();
                if (Objects.nonNull(inputStream)) {
                    byte[] buf = new byte[1024];
                    int len;
                    while ((len = inputStream.read(buf)) > 0) {
                        bos.write(buf, 0, len);
                    }
                }
            }catch (Exception e) {
                bos.write((fileName + e.getMessage()).getBytes(StandardCharsets.UTF_8));
                map.put("fileName", strTime + fileName + ".txt");
                System.out.println("error:222"+e.getMessage());
            } finally {
                if (ObjectUtil.isNotEmpty(inputStream)) {
                    inputStream.close();
                }
                bos.close();
            }
            map.put("outByte", bos.toByteArray());
            files.add(map);
        }
        return files;
    }
  1. 写文件到本地
public void downloadZip(List<Map<String, Object>> maps) throws IOException {
        String downfilepath = "D:\\reloadD\\www\\java\\study\\_2020\\target\\aa.zip";
        ZipOutputStream zipOutputStream = new ZipOutputStream(new FileOutputStream(downfilepath));
        try {
            for (Map<String, Object> map : maps) {
                ZipEntry zipEntry =  new ZipEntry((String) map.get("fileName"));
                zipOutputStream.putNextEntry(zipEntry);
                zipOutputStream.write((byte[]) map.get("outByte"));
            }
        } catch (Exception e) {
            System.out.println("error:");
        } finally {
            zipOutputStream.close();
        }
    }
  1. 下载到本地
	public static void downloadZip(HttpServletResponse response, List<Map<String, Object>> maps) throws IOException {
		String strTime = DateUtil.format(new Date(), "yyyyMMddHHmmss");
		response.setContentType("application/octet-stream");
		response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(strTime + "对账单", "UTF-8") + ".zip");
		ZipOutputStream zipOutputStream = new ZipOutputStream(response.getOutputStream());
		try {
			for (Map<String, Object> map : maps) {
				ZipEntry zipEntry =  new ZipEntry((String) map.get("fileName"));
				zipOutputStream.putNextEntry(zipEntry);
				zipOutputStream.write((byte[]) map.get("outByte"));
			}
		} catch (Exception e) {
			log.error("下载远程文件信息错误信息:" + e.getMessage());
		} finally {
			IoUtil.close(zipOutputStream);
		}
	}

posted on   何苦->  阅读(156)  评论(0编辑  收藏  举报

相关博文:
阅读排行:
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?

导航

< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5
点击右上角即可分享
微信分享提示