java下载文件工具类

package com.skjd.util;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL; import javax.servlet.http.HttpServletResponse; public class DownloadUtils {
/**
* 根据网络url下载文件
* 下载到指定文件
* @throws MalformedURLException
*/
public static void DownloadByUrlToFile(String urlPath,String filename2) throws Exception{
URL url = new URL(urlPath);
/* //文件后缀名
String str = url.getFile().substring( url.getFile().lastIndexOf(".")+1);
//文件名
String filename = url.getFile().substring(url.getFile().lastIndexOf("/")+1,url.getFile().lastIndexOf("."));*/
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
int code = conn.getResponseCode();
if (code != HttpURLConnection.HTTP_OK) {
throw new Exception("文件读取失败");
}
InputStream fis = new BufferedInputStream(conn.getInputStream());
File file = new File(filename2);
OutputStream toClient = new BufferedOutputStream(new FileOutputStream(file));
// 以流的形式下载文件。
byte[] buffer = new byte[*];
int read=;
//如果没有数据了会返回-1;如果还有会返回数据的长度
while ((read = fis.read(buffer))!=-) {
//读取多少输出多少
toClient.write(buffer,,read);
}
toClient.flush();
toClient.close();
fis.close();
}
/**
* 根据网络url下载文件
* 直接返回给浏览器
* @throws MalformedURLException
*/
public static void DownloadByUrl(String urlPath,HttpServletResponse response) throws Exception{
URL url = new URL(urlPath);
//文件后缀名
String str = url.getFile().substring( url.getFile().lastIndexOf(".")+);
//文件名
String filename = url.getFile().substring(url.getFile().lastIndexOf("/")+,url.getFile().lastIndexOf("."));
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
int code = conn.getResponseCode();
if (code != HttpURLConnection.HTTP_OK) {
throw new Exception("文件读取失败");
}
InputStream fis = new BufferedInputStream(conn.getInputStream());
OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
// 设置response的Header
response.addHeader("Content-Disposition", "attachment;filename=" +filename+"."+str);
response.setContentType("application/octet-stream");
// 以流的形式下载文件。
byte[] buffer = new byte[*];
int read=;
//如果没有数据了会返回-1;如果还有会返回数据的长度
while ((read = fis.read(buffer))!=-) {
//读取多少输出多少
toClient.write(buffer,,read);
}
toClient.flush();
toClient.close();
fis.close(); }
}

使用案例代码

/**
* 导出购票码
*/
@RequestMapping(value="/getAllCode")
public void getAllCode(HttpServletResponse response){
PageData pd = new PageData();
pd = this.getPageData();
try {
List<PageData> list = driverService.listAll(pd);
//获取当前项目的绝对路径
String realPath = this.getRequest().getSession().getServletContext().getRealPath("/");
File file = new File(realPath+"/codes/");
//判断是否存在这个文件夹,如果不存在则重新创建一个文件
if(!file.exists()){
file.mkdirs();
}
String url2="";
List<PageData> list3 = dictionariesService.getIMGUrl(null);
for(int i=;i<list3.size();i++){
if(String.valueOf(list3.get(i).get("remarks")).length()>){
url2=String.valueOf(list3.get(i).get("remarks"));
}
}
for(int i=;i<list.size();i++){
if(list.get(i).get("code_url")!=null&&!"".equals(String.valueOf(list.get(i).get("code_url")))){
DownloadUtils.DownloadByUrlToFile(url2+String.valueOf(list.get(i).get("code_url")),realPath+"/codes/"+String.valueOf(list.get(i).get("idcode"))+".png");
}
}
FileZip.zip(realPath+"/codes/", realPath+"/codes.zip");
InputStream fis = new BufferedInputStream(new FileInputStream(new File(realPath+"/codes.zip")));
OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
Cookie cookie = new Cookie("abcd", "");
cookie.setPath("/");
response.addCookie(cookie);
// 设置response的Header
response.setContentType("application/zip");// 指明response的返回对象是文件流
response.setHeader("content-Disposition", "attachment;filename=codes.zip");// 设置在下载框默认显示的文件名
// 以流的形式下载文件。
byte[] buffer = new byte[*];
int read=;
//如果没有数据了会返回-1;如果还有会返回数据的长度
while ((read = fis.read(buffer))!=-) {
//读取多少输出多少
toClient.write(buffer,,read);
}
toClient.flush();
toClient.close();
fis.close(); } catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

java下载文件工具类的更多相关文章

  1. HTTP 下载文件工具类

    ResponseUtils.java package javax.utils; import java.io.ByteArrayInputStream; import java.io.File; im ...

  2. ftp上传或下载文件工具类

    FtpTransferUtil.java工具类,向ftp上传或下载文件: package utils; import java.io.File; import java.io.FileOutputSt ...

  3. java FileUtils 文件工具类

    package com.sicdt.library.core.utils; import java.io.BufferedInputStream; import java.io.File; impor ...

  4. Java 通过Xml导出Excel文件,Java Excel 导出工具类,Java导出Excel工具类

    Java 通过Xml导出Excel文件,Java Excel 导出工具类,Java导出Excel工具类 ============================== ©Copyright 蕃薯耀 20 ...

  5. 自动扫描FTP文件工具类 ScanFtp.java

    package com.util; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import ja ...

  6. 读取Config文件工具类 PropertiesConfig.java

    package com.util; import java.io.BufferedInputStream; import java.io.FileInputStream; import java.io ...

  7. Java 实现删除文件工具类

    工具代码 package com.wangbo; import java.io.File; /** * 删除目录或文件工具类 * @author wangbo * @date 2017-04-11 1 ...

  8. Java常用工具类---IP工具类、File文件工具类

    package com.jarvis.base.util; import java.io.IOException;import java.io.InputStreamReader;import jav ...

  9. java文件工具类

    import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.Fi ...

随机推荐

  1. this指向详解及改变它的指向的方法

    一.this指向详解(彻底理解js中this的指向,不必硬背) 首先必须要说的是,this的指向在函数定义的时候是确定不了的,只有函数执行的时候才能确定this到底指向谁,实际上this的最终指向的是 ...

  2. java实现mysql数据备份

    /** * @param hostIP ip地址,可以是本机也可以是远程 * @param userName 数据库的用户名 * @param password 数据库的密码 * @param sav ...

  3. 自动化运维-Ansible-playbook

    Ansible Playbook https://ansible-tran.readthedocs.io/en/latest/docs/playbooks_intro.html Ansible中文网址 ...

  4. 树莓派配置wifi网络+更换镜像源

    刚安装完系统后,采用的是树莓派通过网线连接笔记本wifi共享方式联网,后面考虑不使用网线,让树莓派使用wifi联网. 一.配置无线网络 1.通过ssh登录树莓派,输入用户名和密码后,输入如下命令进入图 ...

  5. xtrbackup备份,及恢复数据

    模拟定时任务周日备份数据,周一数据变化,周一crontab定时任务增量备份,周二数据变化,周二crontabl增量备份,然后有人删库,我们进行恢复数据 模拟crontab 里的定时任务周日全备 [ro ...

  6. CVE-2019-0193:Apache Solr 远程命令执行漏洞复现

    0x00 漏洞背景 2019年8月1日,Apache Solr官方发布了CVE-2019-0193漏洞预警,漏洞危害评级为严重 0x01 影响范围 Apache Solr < 8.2.0 0x0 ...

  7. python+BeautifulSoup+多进程爬取糗事百科图片

    用到的库: import requests import os from bs4 import BeautifulSoup import time from multiprocessing impor ...

  8. python deque的内在实现 本质上就是双向链表所以用于stack、队列非常方便

    How collections.deque works? Cosven     前言:在 Python 生态中,我们经常使用 collections.deque 来实现栈.队列这些只需要进行头尾操作的 ...

  9. 移动架构师第一站UML建模

    回想一下自己的Android生涯已经经历过N多个年头了,基本都是在编写业务代码,都知道35岁程序员是一个坎,当然如果有能力能做到Android架构师的职位其生命周期也会较长,毕境不是人人都能轻易做到这 ...

  10. python开发应用笔记-SciPy扩展库使用

    SciPy https://www.scipy.org/ SciPy中的数据结构: 1.ndarray(n维数组) 2.Series(变长字典) 3.DataFrame(数据框) NumPy适合于线性 ...