java下载文件工具类
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下载文件工具类的更多相关文章
- HTTP 下载文件工具类
ResponseUtils.java package javax.utils; import java.io.ByteArrayInputStream; import java.io.File; im ...
- ftp上传或下载文件工具类
FtpTransferUtil.java工具类,向ftp上传或下载文件: package utils; import java.io.File; import java.io.FileOutputSt ...
- java FileUtils 文件工具类
package com.sicdt.library.core.utils; import java.io.BufferedInputStream; import java.io.File; impor ...
- Java 通过Xml导出Excel文件,Java Excel 导出工具类,Java导出Excel工具类
Java 通过Xml导出Excel文件,Java Excel 导出工具类,Java导出Excel工具类 ============================== ©Copyright 蕃薯耀 20 ...
- 自动扫描FTP文件工具类 ScanFtp.java
package com.util; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import ja ...
- 读取Config文件工具类 PropertiesConfig.java
package com.util; import java.io.BufferedInputStream; import java.io.FileInputStream; import java.io ...
- Java 实现删除文件工具类
工具代码 package com.wangbo; import java.io.File; /** * 删除目录或文件工具类 * @author wangbo * @date 2017-04-11 1 ...
- Java常用工具类---IP工具类、File文件工具类
package com.jarvis.base.util; import java.io.IOException;import java.io.InputStreamReader;import jav ...
- java文件工具类
import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.Fi ...
随机推荐
- csdn 分享私藏的18个黑科技网站,想找什么软件就找什么软件!!!
https://blog.csdn.net/sinat_33921105/article/details/103307419 1.NO.1–胡萝卜周 http://www.carrotchou.blo ...
- 学习笔记之编程珠玑 Programming Pearls
Programming Pearls (2nd Edition): Jon Bentley: 0785342657883: Amazon.com: Books https://www.amazon.c ...
- linux搭建stm32开发环境
下载stm32固件库 创建目录 libs目录放stm32固件库,src放用户源码,inc放用户头文件 # mkdir libs src inc 复制文件 将STM32F10x_StdPeriph_Li ...
- 在Linux系统上安装Spring boot应用
Unix/Linux 服务 systemd 服务 操作过程 1. 安装了JDK的centOS7虚拟机 注意下载linux版本JDK的时候不能直接通过wget这种直接链接下载,否则会解压不成功,应该打开 ...
- Jmeter配置元件
1.CSV Data Set Config Filename 参数化文件的路径 文件中的数据最后一行不能有空行,空行会被当做一个参数 若要进行分布式压测,可以将参数化文件放在jmeter的bin目 ...
- lvm逻辑卷扩容报错解决
报错: [root@centos21 space]# resize2fs /dev/centos/root resize2fs (-Dec-) resize2fs: Bad magic number ...
- SpringBoot项目打成jar在linux后台运行
--关闭客户端依然进程存在 nohup java -jar spring-boot-hello-1.0.jar 1>/dev/null 2>&1 & --Ctrl+C后不会 ...
- MySQL/MariaDB数据库的服务器配置
MySQL/MariaDB数据库的服务器配置 作者:尹正杰 版权声明:原创作品,谢绝转载!否则将追究法律责任. 一.MySQL中的系统数据库 1>.mysql数据库 是mysql的核心数据库,类 ...
- tomcat下载地址
https://archive.apache.org/dist/tomcat/tomcat-6/v6.0.53/bin/ Index of /dist/tomcat/tomcat-6/v6.0.53 ...
- 万众期待的kintone开发账号免费开放申请啦!
亲爱的小伙伴们,等了很久很久的kintone开发账号终于可以免费申请使用了! 有人想问了,什么是kintone? kintone是指无需开发知识,即可根据公司业务轻松创建系统的Cybozu的云服务. ...