javaweb通过接口来实现多个文件压缩和下载(包括单文件下载,多文件批量下载)

程序员在做web等项目的时候,往往都需要添加文件上传、下载、删除的功能,有时是单文件,有时多文件批量 操作,而这些功能的代码程序员可以自己收藏起来当成工具使用,这样,程序员在进行程序设计的时候就会事半功倍 了,那么接下来的博客将会介绍各个框架的文件上传和下载功能的使用方法。 

  这篇博文主要是讲如何将多个文件压缩并下载下来:

 

 主要有以下几个步骤:

1。 首先先遍历出某个文件夹所含有的所有文件

 

[html] view plain copy

  1. <code class="language-java"><span style="color:#3366ff;">import java.io.File;  
  2. import java.util.Vector;  
  3. public class A {  
  4.  public static void recursion(String root, Vector<String> vecFile) {  
  5. /*根据路径生成一个文件*/  
  6.   File file = new File(root);  
  7.   File[] subFile = file.listFiles();  
  8. /*遍历文件里面的所有文件*/  
  9.   for (int i = 0; i < subFile.length; i++) {  
  10. /*如果是文件夹,则递归下去寻找文件夹里面的文件*/  
  11. if (subFile[i].isDirectory()) { recursion(subFile[i].getAbsolutePath(), vecFile); } else {  
  12. /*如果不是文件夹的话就直接添加到vector容器里面去  
  13. (vector类称作向量类,它实现了动态数组,用于元素数量变化的对象数组。像数组一样,vector类也用从0开始的下标表示元素的位置;但和数组不同的是,当vector对象创建后,数组的元素个数会随着vector对象元素个数的增大和缩小而自动变化。)*/  
  14. 2.将遍历出来的文件进行压缩和下载:  
  15.   
  16. String filename = subFile[i].getName();  
  17.     vecFile.add(filename);  
  18.    }  
  19.   }  
  20.  }  
  21.  public static void main(String[] args) {  
  22.   Vector<String> vecFile = new Vector<String>();  
  23.   recursion("D:/logs/2", vecFile);  
  24.     
  25.   for (String fileName : vecFile) {  
  26.    System.out.println(fileName);  
  27.   }  
  28.  }  
  29. } </span></code>  

2。 将遍历出来的文件进行压缩和下载:(一个一个压缩)

2.1 设置下载文件的名称

 
  1. String fileName = "temp1.zip";

  2. response.setContentType("text/html; charset=UTF-8"); // 设置编码字符

  3. response.setContentType("application/x-msdownload"); // 设置内容类型为下载类型

  4. response.setHeader("Content-disposition", "attachment;filename=" + fileName);// 设置下载的文件名称

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

  6. System.out.println("配置成功");

 

2.2 创建压缩文件需要的空的zip包

 
  1. String zipBasePath = request.getSession().getServletContext().getRealPath("/logs/2/");

  2.  
  3. /* 输出basePath的路径,方便调试 */

  4. System.out.println(zipBasePath);

  5. /* 创建压缩文件需要的空的zip包 ,这里是自动生成的,不用我们自己去生成 */

  6. String zipFilePath = zipBasePath + "temp.zip";

  7. System.out.println("create the empty zip file successfully??????");

 

2.3 根据临时的zip压缩包路径,创建zip文件

 
  1. File zip = new File(zipFilePath);

  2. if (!zip.exists()) {

  3. zip.createNewFile();

  4. }

  5. System.out.println("create the zip file successfully");

 

2.4 创建zip文件输出流

 
  1. FileOutputStream fos = new FileOutputStream(zip);

  2. ZipOutputStream zos = new ZipOutputStream(fos);

  3. System.out.println("create the empty zip stream successfully");

 

2.5 循环读取文件路径集合,获取每一个文件的路径(将文件一个一个进行压缩)

 
  1. for (String fp : vecFile) {

  2. File f = new File(fp); // 根据文件路径创建文件

  3. zipFile(f, zos); // 将每一个文件写入zip文件包内,即进行打包

  4. }

  5. System.out.println("get the path successfully");

 
  1.                // fos.close();//如果这样关两次的话会报错,java.io.IOException: Stream closed

  2.                 zos.close();

  3. System.out.println("ok??");

 

2.6 将打包后的文件写到客户端,有两种方法可以实现(下面会进行介绍),这里使用缓冲流输出

 
  1. InputStream fis = new BufferedInputStream(new FileInputStream(zipFilePath));

  2. byte[] buff = new byte[4096];

  3. int size = 0;

  4. while ((size = fis.read(buff)) != -1) {

  5. out.write(buff, 0, size);

  6. }

  7. System.out.println("package is packed successfully");

 

2.7 释放和关闭输入输出流

 
  1.                 out.flush();//清楚缓存

  2. out.close();

  3. fis.close();

 

2.8 文件压缩的方法

 
  1. public void zipFile(File inputFile, ZipOutputStream zipoutputStream) {

  2. try {

  3. if (inputFile.exists()) { // 判断文件是否存在

  4. if (inputFile.isFile()) { // 判断是否属于文件,还是文件夹

  5.  
  6. // 创建输入流读取文件

  7. FileInputStream fis = new FileInputStream(inputFile);

  8. BufferedInputStream bis = new BufferedInputStream(fis);

  9.  
  10. // 将文件写入zip内,即将文件进行打包

  11. ZipEntry ze = new ZipEntry(inputFile.getName()); // 获取文件名

  12. zipoutputStream.putNextEntry(ze);

  13.  
  14. // 写入文件的方法,同上

  15. byte[] b = new byte[1024];

  16. long l = 0;

  17. while (l < inputFile.length()) {

  18. int j = bis.read(b, 0, 1024);

  19. l += j;

  20. zipoutputStream.write(b, 0, j);

  21. }

  22. // 关闭输入输出流

  23. bis.close();

  24. fis.close();

  25. } else { // 如果是文件夹,则使用穷举的方法获取文件,写入zip

  26. try {

  27. File[] files = inputFile.listFiles();

  28. for (int i = 0; i < files.length; i++) {

  29. zipFile(files[i], zipoutputStream);

  30. }

  31. } catch (Exception e) {

  32. e.printStackTrace();

  33. }

  34. }

  35. }

  36. } catch (Exception e) {

  37. e.printStackTrace();

  38. }

  39. }

  40.  

 

这个是我在团队中的一个项目开发过程。在这个过程中,我主要遇到了几个常见的问题,不过最后都一一被我解决掉了。

1. 因为我要下载压缩的文件是一个日志不断动态生成的文件,所以需要先对其复制到另外一个文件夹再进行压缩以及下载;

2. 对IO流的一些 知识不是很熟悉(学习并参考:https://blog.csdn.net/weixin_37766296/article/details/80070847)

 

文件从一个文件夹复制到另一个文件夹:

 
  1. // 读写文件

  2. public static void copy1() throws Exception{

  3. FileInputStream fis = new FileInputStream("C:\\Users\\Administrator\\Desktop\\1\\log.txt");(原文件路径)

  4. FileOutputStream fos = new FileOutputStream("D:\\java1\\eclipse\\javadownload\\.metadata\\.plugins\\org.eclipse.wst.server.core\\tmp1\\wtpwebapps\\SCNU_OAuth2\\logs\\1\\log.txt");

  5. int len = 0;

  6. byte[] buf = new byte[1024];

  7. while ((len = fis.read(buf)) != -1) {

  8. fos.write(buf, 0, len);

  9. }

  10. fos.close();

  11. fis.close();

  12. }

 
  1. /*复制过去之后格式发生了变化,故放弃这个方法*/

  2. public void copy2() {

  3. FileWriter fw = null;

  4. BufferedReader br = null;

  5. try {

  6. fw = new FileWriter(

  7. "D:\\java1\\eclipse\\javadownload\\.metadata\\.plugins\\org.eclipse.wst.server.core\\tmp1\\wtpwebapps\\SCNU_OAuth2\\logs\\1\\log.txt",

  8. true);

  9. br = new BufferedReader(new InputStreamReader(

  10. new FileInputStream("C:\\Users\\Administrator\\Desktop\\1\\log.txt"), "UTF-8"));(原文件路径)

  11. String line = null;

  12. while ((line = br.readLine()) != null) {

  13. // System.out.println("文件内容: " + line);

  14. fw.write(line);

  15. fw.flush();

  16. }

  17. br.close();

  18. } catch (FileNotFoundException e) {

  19. e.printStackTrace();

  20. } catch (IOException e) {

  21. e.printStackTrace();

  22. } finally {

  23. if (fw != null) {

  24. try {

  25. fw.close();

  26. } catch (IOException e) {

  27. // TODO Auto-generated catch block

  28. e.printStackTrace();

  29. }

  30. }

  31. }

  32. }


 

对于单个文件下载:

可以参考:https://blog.csdn.net/alan_liuyue/article/details/72772502

参考博文:https://blog.csdn.net/alan_liuyue/article/details/72772502(里面关于流的关闭有点瑕疵)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值