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写入、读取文本

    文本写入 public static void createFile(String input) throws IOException { //设置文件路径 String filePath = &qu ...

  2. js模块基础练习题

    题目描述 完成函数 createModule,调用之后满足如下要求: 1.返回一个对象 2.对象的 greeting 属性值等于 str1, name 属性值等于 str2 3.对象存在一个 sayI ...

  3. 如何解决div背景色半透明,里面的图片不透明问题

    用rgba可以实现,不能用opacity 背景做成透明的背景图,opacity属性影响子集的,除非把两者独立开~

  4. CSS-图片整合笔记

    注意点: 概念:图片整合技术( css sprite 或 精灵图).通过将多个图片融合到一张图片,然后通过CSS background 背景定位技术技巧布局网页背景 优势:减少 http iis 请求 ...

  5. Appscan漏洞之会话标识未更新

    本次针对 Appscan漏洞 会话标识未更新 进行总结,如下: 1. 会话标识未更新 1.1.攻击原理 在认证用户或者以其他方式建立新用户会话时,如果不使任何现有会话标识失效,攻击者就有机会窃取已认证 ...

  6. 个人项目 wc(java实现)

    一.Github网址: https://github.com/Clarazhangbw/Wc.exe 二.PSP表 PSP2.1 Personal Software Process Stages 预估 ...

  7. 将html版API文档转换成chm格式的API文档

    文章完全转载自: https://blog.csdn.net/u012557538/article/details/42089277 将html版API文档转换成chm格式的API文档并不是一件难事, ...

  8. php 文件包含 include、include_once、require、require_once

    简言之,include某文件:把某文件的代码粘过来,如果该文件不存在,也继续执行下面的代码,带_once的是看看之前引用过没,引用过就不引用了(_once这行代码的心里活动:“之后引用过没有我不关心, ...

  9. mysqlbinlog 恢复数据到任意时间点

    创建表,插入数据. ``` mysql> create database binlog; mysql> create table bt(id int); mysql> insert ...

  10. MySQL重置自增id

    专注和简单一直是我的秘诀之一,简单的事情可能比复杂更难做到,你必须努力理清思路,从而使其便的简单:但这最终是值得的,因为你一旦做到了,便可创造奇迹. ---乔布斯 #删除所有数据 delete  fr ...