这篇文章主要介绍了java文件下载代码实例(单文件下载和多文件打包下载),文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下

最近项目有需要写文件下载相关代码,这边提交记录下相关代码模块,写的不太好,后期再优化相关代码,有好的建议,可留言,谢谢。

1)单文件下载

public String oneFileDownload(HttpServletRequest request,HttpServletResponse response){

//针对需求需要与需求沟通下载文件传递参数

//目前demo文件名是文件的hashCode值+后缀名的方式命名,可以默认该hashCode值为文件唯一id

String fileName = request.getParameter("fileName");

if(StringUtils.isBlank(fileName)){

return "文件名为空";

}

String filePath = request.getSession().getServletContext().getRealPath("/convert")+File.separator+fileName;//目前文件默认在该文件夹下,后续变动需修改

File downloadFile = new File(filePath);

if(downloadFile.exists()){

OutputStream out = null;

FileInputStream fis = null;

BufferedInputStream bis = null;

try {

if(downloadFile.isDirectory()){

return "路径错误仅指向文件夹";

}

out = response.getOutputStream();// 创建页面返回方式为输出流,弹出下载框

fis = new FileInputStream(downloadFile);

bis = new BufferedInputStream(fis);

response.setContentType("application/pdf; charset=UTF-8");//设置编码字符

response.setHeader("Content-disposition", "attachment;filename=" + fileName);

byte[] bt = new byte[2048];

int size = 0;

while((size=bis.read(bt)) != -1){

out.write(bt, 0, size);

}

} catch (Exception e) {

e.printStackTrace();

}finally {

try {

//关闭流

out.flush();

if(out != null){

out.close();

}

if(bis != null){

bis.close();

}

if(fis != null){

fis.close();

}

} catch (Exception e2) {

e2.printStackTrace();

}

}

return "下载成功";

}else{

return "文件不存在!";

}

}

2)多文件打包下载

a)下载指定文件夹下的文件,如果嵌套文件夹也支持(但文件名需要唯一)

public String zipDownload(HttpServletRequest request,HttpServletResponse response) throws IOException{

String sourceFilePath = request.getSession().getServletContext().getRealPath("/convert");//文件路径

String destinFilePath = request.getSession().getServletContext().getRealPath("/fileZip");

String fileName = FileUtil.zipFiles(sourceFilePath, destinFilePath);

File file = new File(destinFilePath+File.separator+fileName);

response.setHeader("Content-disposition", "attachment;filename=" + fileName);

if(file.exists()){

FileInputStream fis = null;

BufferedInputStream bis = null;

OutputStream out = response.getOutputStream();

try {

fis = new FileInputStream(file);

bis = new BufferedInputStream(fis);

byte[] bufs = new byte[1024 * 10];

int read = 0;

while ((read = bis.read(bufs, 0, 1024 * 10)) != -1) {

out.write(bufs, 0, read);

}

} catch (FileNotFoundException e) {

e.printStackTrace();

}finally {

if(bis != null){

bis.close();

}

if(out!=null){

out.close();

}

File zipFile = new File(destinFilePath+File.separator+fileName);

if(zipFile.exists()){

zipFile.delete();

}

}

}else{

return "文件压缩失败";

}

return "下载成功";

}

b)下载指定文件夹下的所有文件,支持树型结构

public String zipDownloadRelativePath(HttpServletRequest request,HttpServletResponse response) {

String msg ="";//下载提示信息

String root = request.getSession().getServletContext().getRealPath("/convert");//文件路径

Vector fileVector = new Vector();//定义容器装载文件

File file = new File(root);

File [] subFile = file.listFiles();

//判断文件性质并取文件

for(int i = 0; i

if(!subFile[i].isDirectory()){//不是文件夹并且不为空

fileVector.add(subFile[i]);//装载文件

}else{//是文件夹,再次递归遍历文件夹里面的文件

File [] files = subFile[i].listFiles();

Vector v = FileUtil.getPathAllFiles(subFile[i],new Vector());

fileVector.addAll(v);//把迭代的文件装到容器中

}

}

//设置文件下载名称

SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmss");

String fileName = dateFormat.format(new Date())+".zip";

response.setHeader("Content-disposition", "attachment;filename=" + fileName);//如果有中文需要转码

//定义相关流

//用于浏览器下载响应

OutputStream out = null;

//用于读压缩好的文件

BufferedInputStream bis = null;//用缓存性能会好一些

//用于压缩文件

ZipOutputStream zos = null;

//创建一个空的zip文件

String zipBasePath = request.getSession().getServletContext().getRealPath("/fileZip");

String zipFilePath = zipBasePath+File.separator+fileName;

File zipFile = new File(zipFilePath);

try {

if(!zipFile.exists()){//不存在创建一个新的

zipFile.createNewFile();

}

out = response.getOutputStream();

//创建文件输出流

zos = new ZipOutputStream(new FileOutputStream(zipFile));

//循环文件,一个一个按顺序压缩

for(int i = 0;i< fileVector.size();i++){

System.out.println(fileVector.get(i).getName()+"大小为:"+fileVector.get(i).length());

FileUtil.zipFileFun(fileVector.get(i),root,zos);

}

//压缩完成以后必须要在此处执行关闭 否则下载文件会有问题

if(zos != null){

zos.closeEntry();

zos.close();

}

byte[] bt = new byte[10*1024];

int size = 0;

bis = new BufferedInputStream(new FileInputStream(zipFilePath),10*1024);

while((size=bis.read(bt,0,10*1024)) != -1){//没有读完

out.write(bt,0,size);

}

} catch (Exception e) {

e.printStackTrace();

}finally {//关闭相关流

try {

//避免出异常时无法关闭

if(zos != null){

zos.closeEntry();

zos.close();

}

if(bis != null){

bis.close();

}

if(out != null){

out.close();

}

if(zipFile.exists()){

zipFile.delete();//删除

}

} catch (Exception e2) {

System.out.println("流关闭出错!");

}

}

return "下载成功";

}

下载辅助工具类

package com.hhwy.fileview.utils;

import java.io.BufferedInputStream;

import java.io.BufferedOutputStream;

import java.io.File;

import java.io.FileInputStream;

import java.io.FileNotFoundException;

import java.io.FileOutputStream;

import java.io.IOException;

import java.text.SimpleDateFormat;

import java.util.Date;

import java.util.Vector;

import java.util.zip.ZipEntry;

import java.util.zip.ZipOutputStream;

public class FileUtil {

/**

* 把某个文件路径下面的文件包含文件夹压缩到一个文件下

* @param file

* @param rootPath 相对地址

* @param zipoutputStream

*/

public static void zipFileFun(File file,String rootPath,ZipOutputStream zipoutputStream){

if(file.exists()){//文件存在才合法

if(file.isFile()){

//定义相关操作流

FileInputStream fis = null;

BufferedInputStream bis = null;

try {

//设置文件夹

String relativeFilePath = file.getPath().replace(rootPath+File.separator, "");

//创建输入流读取文件

fis = new FileInputStream(file);

bis = new BufferedInputStream(fis,10*1024);

//将文件装入zip中,开始打包

ZipEntry zipEntry;

if(!relativeFilePath.contains("\\")){

zipEntry = new ZipEntry(file.getName());//此处值不能重复,要唯一,否则同名文件会报错

}else{

zipEntry = new ZipEntry(relativeFilePath);//此处值不能重复,要唯一,否则同名文件会报错

}

zipoutputStream.putNextEntry(zipEntry);

//开始写文件

byte[] b = new byte[10*1024];

int size = 0;

while((size=bis.read(b,0,10*1024)) != -1){//没有读完

zipoutputStream.write(b,0,size);

}

} catch (Exception e) {

e.printStackTrace();

}finally {

try {

//读完以后关闭相关流操作

if(bis != null){

bis.close();

}

if(fis != null){

fis.close();

}

} catch (Exception e2) {

System.out.println("流关闭错误!");

}

}

}

// else{//如果是文件夹

// try {

// File [] files = file.listFiles();//获取文件夹下的所有文件

// for(File f : files){

// zipFileFun(f,rootPath, zipoutputStream);

// }

// } catch (Exception e) {

// e.printStackTrace();

// }

//

// }

}

}

/*

* 获取某个文件夹下的所有文件

*/

public static Vector getPathAllFiles(File file,Vector vector){

if(file.isFile()){//如果是文件,直接装载

System.out.println("在迭代函数中文件"+file.getName()+"大小为:"+file.length());

vector.add(file);

}else{//文件夹

File[] files = file.listFiles();

for(File f : files){//递归

if(f.isDirectory()){

getPathAllFiles(f,vector);

}else{

System.out.println("在迭代函数中文件"+f.getName()+"大小为:"+f.length());

vector.add(f);

}

}

}

return vector;

}

/**

* 压缩文件到指定文件夹

* @param sourceFilePath 源地址

* @param destinFilePath 目的地址

*/

public static String zipFiles(String sourceFilePath,String destinFilePath){

File sourceFile = new File(sourceFilePath);

FileInputStream fis = null;

BufferedInputStream bis = null;

FileOutputStream fos = null;

ZipOutputStream zos = null;

SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmss");

String fileName = dateFormat.format(new Date())+".zip";

String zipFilePath = destinFilePath+File.separator+fileName;

if (sourceFile.exists() == false) {

System.out.println("待压缩的文件目录:" + sourceFilePath + "不存在.");

} else {

try {

File zipFile = new File(zipFilePath);

if (zipFile.exists()) {

System.out.println(zipFilePath + "目录下存在名字为:" + fileName + ".zip" + "打包文件.");

} else {

File[] sourceFiles = sourceFile.listFiles();

if (null == sourceFiles || sourceFiles.length < 1) {

System.out.println("待压缩的文件目录:" + sourceFilePath + "里面不存在文件,无需压缩.");

} else {

//读取sourceFile下的所有文件

Vector vector = FileUtil.getPathAllFiles(sourceFile, new Vector());

fos = new FileOutputStream(zipFile);

zos = new ZipOutputStream(new BufferedOutputStream(fos));

byte[] bufs = new byte[1024 * 10];

for (int i = 0; i < vector.size(); i++) {

// 创建ZIP实体,并添加进压缩包

ZipEntry zipEntry = new ZipEntry(vector.get(i).getName());//文件不可重名,否则会报错

zos.putNextEntry(zipEntry);

// 读取待压缩的文件并写进压缩包里

fis = new FileInputStream(vector.get(i));

bis = new BufferedInputStream(fis, 1024 * 10);

int read = 0;

while ((read = bis.read(bufs, 0, 1024 * 10)) != -1) {

zos.write(bufs, 0, read);

}

}

}

}

} catch (FileNotFoundException e) {

e.printStackTrace();

throw new RuntimeException(e);

} catch (IOException e) {

e.printStackTrace();

throw new RuntimeException(e);

} finally {

// 关闭流

try {

if (null != bis)

bis.close();

if (null != zos)

zos.closeEntry();

zos.close();

} catch (IOException e) {

e.printStackTrace();

throw new RuntimeException(e);

}

}

}

return fileName;

}

}

这边自测试全部可以正常使用,代码质量不高

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。

java 文件下载代码_java文件下载代码实例(单文件下载和多文件打包下载)相关推荐

  1. php本地文件打包代码,PHP实战:几行代码轻松实现PHP文件打包下载zip

    <PHP实战:几行代码轻松实现PHP文件打包下载zip>要点: 本文介绍了PHP实战:几行代码轻松实现PHP文件打包下载zip,希望对您有用.如果有疑问,可以联系我们. PHP应用 //获 ...

  2. Java如何实现文件打包下载功能

        在日常项目开发中,我们会经常遇到,上传下载以及打包的常用功能,本节中就如何利用JAva自带的类库,实现zip压缩打包文件下载进行详细说明.注:不支持中文文件名,可在上传时就重命名文件名称.(下 ...

  3. java 文件打包下载

    话不多说,直接上代码 方法需要传入文件目录,比如想打包1目录下的2目录,同时2目录包含3和4目录,name就传入1目录就可以了 打包之后 /*** 文件打包下载** @param src 需要打包的文 ...

  4. java入栈_java中代码块的执行,也会有入栈的步骤吗?

    首先这个问题很有意思,不过题主没具体指明放在何处的代码块. 这里至少有三种情况,第一种就是在普通的方法里面,第二种是实例初始化代码块,第三种是静态初始化代码块. 第一种情况 使用javap反汇编了一下 ...

  5. 监控系统java调用摄像头_java调用摄像头实例

    [实例简介] java调用摄像头实例,包含所需要的jar文件,下载即可运行. [实例截图] [核心代码] d7850a13-8dbf-42bb-934c-0f911d9ed010 └── Xuggle ...

  6. java金字塔数字代码_Java基础代码实例 :在控制台中输出金字塔,这个金字塔是由左右对称的数字组成的。 | 学步园...

    package test; public class testt { public static void main(String[] args) { int row1 = 13; // 声明行数 f ...

  7. java http 表单提交_java模仿http表单提交数据(含文件上传)实例源码

    [实例简介]java模仿http表单提交数据.模仿http表单上传文件示例 [实例截图] [核心代码] package com.snca.cloudsign.main; import java.io. ...

  8. java 定时器代码_Java定时器代码的编写

    Java定时器代码的编写 在某些时候, 我们需要实现这样的`功能,某一程序隔一段时间执行一次,而这一事情由系统本身来完成,并不是人为的触发,我们一般可称此为定时器任务.其实到Java中,实现起来是非常 ...

  9. java 微型数据库_Java 9代码工具:使用Java微型基准测试工具的实践会话

    java 微型数据库 用肉眼看,基准测试似乎只是确定执行某些代码需要花费多长时间的简单问题. 但是,通常情况下,这是幼稚的方法. 提供具有准确和可重复结果的有意义的基准并非易事. 在本文中,我们将向您 ...

最新文章

  1. 万字总结:学习MySQL优化原理,这一篇就够了!
  2. 转:D3DXVec3TransformNormal() 与 3DXVec3TransformCoord() 的区别
  3. oracle multi read,解读Oracle12.2体系架构:Filesystem与Multitenant
  4. 教你29招,让你在社交,职场上人人对你刮目相看
  5. c mysql 双主复制_mysql双主复制总结
  6. mysql的引双向链表_一分钟掌握MySQL的InnoDB引擎B+树索引
  7. docker安装zookeeper
  8. 我的文件夹下面有汉字的路径,matlab 不识别
  9. 程序员被怼!HR:对不起,我们不招“精通Excel”的程序员
  10. 从技术问题变成RPWT
  11. CTFHub技能树——备份文件下载
  12. iOS 图片引起的崩溃
  13. 拆解SSK SCRM330 USB3.0读卡器 GL3233 固件 0819
  14. zabbix的php最低版本,ZABBIX企业监控实践(3):升级与配置PHP
  15. Django分页组件
  16. 安大计算机学院李伟教授,安徽大学高教所研究生导师聘任仪式在我校举行
  17. bearer token头_BearerToken之JWT的介绍
  18. 智能高低配电柜无线联网解决方案
  19. 第四期“一生一芯”来了,欢迎报名
  20. android opencv 银行卡识别,【opencv小应用】银行卡号识别(一)

热门文章

  1. RB-PEG-NHS;NHS-PEG-Rhodamine罗丹明聚乙二醇琥珀酰亚胺 红色荧光染料罗丹明B功能化聚乙二醇
  2. 分页查询的SQL优化
  3. DockerCompose快速部署分布式应用,集群部署微服务
  4. 谷歌浏览器无法携带cookie问题
  5. 周珍:微博论道:挨踢人,请关注自己的生命本钱
  6. Python 定义类和构造方法
  7. JAVA语言强制类型转换要求
  8. linux中.tar文件怎么解压
  9. 大数据战略:从数据大国到数据强国
  10. Wondershare DVD Creator for Mac(强大的DVD工具箱)