java 下载文件

本文介绍了一个使用Java实现的文件下载方法。该方法通过输入文件路径和名称,利用HTTP响应将指定文件下载到客户端。文中详细展示了如何设置HTTP响应头、处理文件流以及异常情况。

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

public static void downFile(String filepath,String fileName,HttpServletResponse response) { 
           FileInputStream fileinputstream = null;
           PrintWriter out = null;
           try {  
           response.reset();  
//           File file = new File(filepath +EmoneyConstants.MARK_SLASH+ fileName);
           File file = new File(filepath + fileName);
           if (file.exists()) {
            response.setContentType("application/x-download");// 设置response内容的类型
            response.setHeader("Content-disposition","attachment;filename="+ URLEncoder.encode(fileName, "UTF-8"));// 设置头部信息   
            fileinputstream = new FileInputStream(file);
            out = response.getWriter();
            int i;   
            //开始向网络传输文件流    
            while ((i = fileinputstream.read()) != -1) {
               out.write(i);
               } 
           } else{
            log.error("FileUtils downFile File not found!!!!");
           }
           if(out != null) out.flush();
           if(out != null) out.close();
           if(fileinputstream != null) fileinputstream.close();
           } catch (Exception e) {
            log.error("FileUtils downFile Exception " + e);
           }finally{
            try{
            if(out != null)  out.close();
                if(fileinputstream != null)fileinputstream.close();
              } catch (IOException ee) {
               log.error(" download failed !! " + ee);
              }
           }
        }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值