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. Java知识回顾 (13)序列化

    本资料来自于runoob,略有修改. 整个过程都是 Java 虚拟机(JVM)独立的,也就是说,在一个平台上序列化的对象可以在另一个完全不同的平台上反序列化该对象. 类 ObjectInputStre ...

  2. Python illustrating Downhill simplex method for minimizing the user-supplied scalar function的代码

    学习过程,把代码过程较好的代码段做个记录,如下的代码段是关于Python illustrating Downhill simplex method for minimizing the user-su ...

  3. c# 泛型study

    1.引用类型约束:  类型实参包含任何类,接口,数组,委托,或者是已知是引用类型的另一个类型参数 class demo<T> where T:class 有效的封闭区间demo<St ...

  4. Maven nexus 安装nexus : wrapper | OpenSCManager failed - 拒绝访问。 (0x5)

    在win7中安装nexus时提示:wrapper | OpenSCManager failed - 拒绝访问. (0x5) 主要是没有权限.需要以管理员的身份运行 如果你是直接点击 start-nex ...

  5. Python入门篇-返回值和作用域

    Python入门篇-返回值和作用域 作者:尹正杰 版权声明:原创作品,谢绝转载!否则将追究法律责任. 一.返回值 1>.返回值概述 Python函数使用return语句返回“返回值” 所有函数都 ...

  6. 前端安全问题之CSRF和XSS

    一.CSRF 1.什么是 CSRF CSRF(全称 Cross-site request forgery),即跨站请求伪造 2.攻击原理 用户登录A网站,并生成 Cookie,在不登出的情况下访问危险 ...

  7. Codeforces F. Vus the Cossack and Numbers(贪心)

    题目描述: D. Vus the Cossack and Numbers Vus the Cossack has nn real numbers aiai. It is known that the ...

  8. Codeforces C.Neko does Maths

    题目描述: C. Neko does Maths time limit per test 1 second memory limit per test 256 megabytes input stan ...

  9. [转]Linux-虚拟网络设备-tun/tap

    转: 原文:https://blog.csdn.net/sld880311/article/details/77854651 ------------------------------------- ...

  10. 项目alpha冲刺-测试

    作业要求 这个作业属于哪个课程 软件工程1916-W(福州大学) 这个作业要求在哪里 项目Alpha冲刺 团队名称 基于云的胜利冲锋队 项目名称 云评:高校学生成绩综合评估及可视化分析平台 这个作业的 ...