通过InputStream下载文件

本文详细讲解了如何通过HttpURLConnection实现文件下载,包括处理中文文件名、设置Content-Disposition以及异常处理。同时介绍了如何使用ZipArchiveOutputStream打包多个文件为压缩包的过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

开头:本文着重通过InputStream流下载文件,通过get/post请求获取InputStream下载文件

核心代码:

其中uri:是文件的下载地址(在浏览器中可以直接通过此地址进行文件下载,在这里我们将该地址进行二次封装)

public void download(HttpServletResponse response) throws IOException {
   []byte buffer = download();
   // 清空response
   response.reset();
   // 设置response的Header
   response.addHeader("Content-Disposition", "attachment;filename=" +
           new String("filename".getBytes(StandardCharsets.UTF_8), StandardCharsets.ISO_8859_1));//处理中文乱码
   OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
   response.setContentType("application/octet-stream");
   toClient.write(cadInfoVO.getBuffer());
   toClient.flush();
   toClient.close();
}
public byte[] download() {
   InputStream fis = null;
   try {
       fileName = URLEncoder.encode(fileName,"UTF-8");
       String uri = "文件下载地址"

       try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
           HttpGet httpGet = new HttpGet(uri);
           try (CloseableHttpResponse execute = httpClient.execute(httpGet)) {
               if (execute.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
                   throw new RuntimeException("请求第三方接口失败");
               }
               HttpEntity entity = execute.getEntity();
               fis = entity.getContent();
               byte[] buffer = readInputStream(fis);

               fis.read(buffer);
               return buffer;
           }
       }
   } catch (IOException e) {
       throw new RuntimeException("下载失败",e);
   } finally {
       try {
           assert fis != null;
           fis.close();
       } catch (IOException e) {
           throw new RuntimeException("关闭流失败",e);
       }
   }
}
/**
 * 从输入流中获取数据
 * @param fis 输入流
 * @return
 * @throws Exception
 */
private byte[] readInputStream(InputStream fis) throws IOException {
    ByteArrayOutputStream outStream = new ByteArrayOutputStream();
    byte[] buffer = new byte[1024];
    int len;
    while( (len=fis.read(buffer)) != -1 ){
        outStream.write(buffer, 0, len);
    }
    //fis.close();此处一定不能关闭流
    return outStream.toByteArray();
}

如果需要下载压缩包则使用下方代码替换第一段代码即可:

public void downloadAll(HttpServletResponse response) throws Exception {
    response.reset();
    response.setContentType("content-type:octet-stream;charset=UTF-8");
    response.setHeader("Content-Disposition", "attachment;filename=" +
            new String("filename".getBytes(StandardCharsets.UTF_8), StandardCharsets.ISO_8859_1)+".zip");
    ServletOutputStream out = response.getOutputStream();
    ZipArchiveOutputStream zous = new ZipArchiveOutputStream(out);
    zous.setUseZip64(Zip64Mode.AsNeeded);

    for(/**需要循环的文件列表*/) {
        byte[] buffer = download();
        //设置文件名
        ArchiveEntry entry = new ZipArchiveEntry("filename");
        zous.putArchiveEntry(entry);
        zous.write(buffer);
        zous.closeArchiveEntry();
    }
    zous.close();
}

如有不理解的地方欢迎来扰

Java中,如果你有一个文件InputStream,可以直接使用FileOutputStream将其复制到本地文件系统,实现下载功能。下面是一个简单的示例: ```java import java.io.*; public class FileDownload { public static void downloadFileByInputStream(InputStream is, String fileName) throws IOException { FileOutputStream fos = null; try { // 创建目标文件 File outputFile = new File(fileName); // 检查文件是否存在,如果存在则先删除 if (outputFile.exists()) { outputFile.delete(); } // 打开目标文件的输出流 fos = new FileOutputStream(outputFile); // 将InputStream的数据写入到文件中 byte[] buffer = new byte[1024]; int bytesRead; while ((bytesRead = is.read(buffer)) != -1) { fos.write(buffer, 0, bytesRead); } System.out.println("File downloaded successfully!"); } finally { // 确保关闭资源 if (fos != null) { fos.close(); is.close(); } } } public static void main(String[] args) { try { // 假设你有一个名为inputStreamInputStream // 实际上,这应该是网络请求或者其他数据来源得到的流 InputStream inputStream = ...; String destinationFilePath = "path/to/downloaded/file.txt"; // 目标文件路径 downloadFileByInputStream(inputStream, destinationFilePath); } catch (IOException e) { e.printStackTrace(); } } } ``` 在这个例子中,`downloadFileByInputStream`函数接收一个InputStream和一个文件名,将InputStream中的数据连续写入到一个新的文件中。确保在操作完成后关闭流以释放资源。
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值