JAVA 大文件压缩极速下载

前言

之前大/多文件压缩 900M下载需要7分钟左右,是因为没有优化代码,网上的代码直接复制粘贴能跑就OK,后来因为需求要求大文件1分钟左右下载完,于是各种百度,各种试验,最终产出了2种方案,一种是找迅雷接口,借助迅雷将多文件大文件下载,这种效率很高,而且不占JAVA JVM内耗,但老板觉得用这软件还得装一个插件,于是另想办法,这个方法于是横空出世,900M 压缩仅20秒左右,下载到本地是看网络流量大小。

这里感谢这位博主,大家可以看看这位博主的,我是直接在此博主的代码基础上改进了以迎合我的需求。
https://blog.csdn.net/ahau10/article/details/52550430/

以下直接代码

以下是controller代码(不重要) 代码片.

 @ResponseBody  //高速压缩下载  2019.6.20@RequestMapping(value = "/downloadfileorfolderforzip")public void downloadfileorfolderforzip(String urlsStr, HttpServletResponse response, HttpSession session, HttpServletRequest request) throws Exception {Cookie[] cookies = request.getCookies();if (null==cookies) {System.out.println("没有cookie==============");} else {for(Cookie cookie : cookies){if(cookie.getName().equals("downloadstatus")){cookie.setValue(null);cookie.setMaxAge(0);// 立即销毁cookiecookie.setPath("/");System.out.println("被删除的cookie名字为:"+cookie.getName());response.addCookie(cookie);break;}}}String[] urlss = urlsStr.split(",");List<String> urls = new ArrayList<String>();for(String str : urlss) {urls.add(str);}String filename = new Date().getTime() + ".zip";final File result = new File(this.finalDirPath + "linshi/" + filename);new HighEffiCompressZipTest().createZipFile(urls, result);BufferedInputStream bufferedInputStream = null;OutputStream outputStream = null;try {response.setHeader("content-type", "application/octet-stream");response.setContentType("application/octet-stream");response.setCharacterEncoding("UTF-8");response.setHeader("Content-Disposition", "attachment;filename=" + new String(filename.getBytes(), "iso-8859-1"));byte[] buff = new byte[1024];outputStream = response.getOutputStream();FileInputStream fis = new FileInputStream(result);bufferedInputStream = new BufferedInputStream(fis);int num = bufferedInputStream.read(buff);Cookie cookie = new Cookie("downloadstatus", String.valueOf(new Date().getTime()));cookie.setMaxAge(5 * 60);// 设置为30mincookie.setPath("/");response.addCookie(cookie);while (num != -1) {outputStream.write(buff, 0, num);outputStream.flush();num = bufferedInputStream.read(buff);}System.out.println("==================complete========");} catch (IOException e) {logger.error(e.getMessage(), e);e.printStackTrace();throw e;} finally {System.out.println("==================complete========");if (bufferedInputStream != null) {bufferedInputStream.close();}}}

以下是压缩代码(不重要) 代码片.

public class HighEffiCompressZipTest {public static void main(String[] arg) throws Exception {long begin = System.currentTimeMillis();System.out.println(new Date());final File result = new File("E:/myFile/test.zip");List<String> urls = new ArrayList<String>();urls.add("C:\\Users\\Administrator\\Desktop\\test\\000001 (1).exe");urls.add("C:\\Users\\Administrator\\Desktop\\test\\000001 (1) - 副本.exe");urls.add("C:\\Users\\Administrator\\Desktop\\test\\000001 (2) - 副本.exe");urls.add("C:\\Users\\Administrator\\Desktop\\test\\000001 (3) - 副本.exe");new HighEffiCompressZipTest().createZipFile(urls, result);long end = System.currentTimeMillis();System.out.println("用时:" + (end - begin) + " ms");System.out.println(new Date());}class CustomInputStreamSupplier implements InputStreamSupplier {private File currentFile;public CustomInputStreamSupplier(File currentFile) {this.currentFile = currentFile;}@Overridepublic InputStream get() {try {// InputStreamSupplier api says:// 返回值:输入流。永远不能为Null,但可以是一个空的流return currentFile.isDirectory() ? new NullInputStream(0) : new FileInputStream(currentFile);} catch (FileNotFoundException e) {e.printStackTrace();}return null;}}private void  addEntry(String entryName, File currentFile, HighEffiCompressZip scatterSample) throws IOException {ZipArchiveEntry archiveEntry = new ZipArchiveEntry(entryName);archiveEntry.setMethod(ZipEntry.DEFLATED);final InputStreamSupplier supp = new CustomInputStreamSupplier(currentFile);scatterSample.addEntry(archiveEntry, supp);}private void compressCurrentDirectory(List<String> dir, HighEffiCompressZip scatterSample) throws IOException {if (dir == null) {throw new IOException("源路径不能为空!");}String relativePath = "";
//       // if (dir.isFile()) {//           // relativePath = dir.getName();
//            addEntry("download", null, scatterSample);
//            return;
//        }//        // 空文件夹
//        if (dir.listFiles().length == 0) {//            relativePath = dir.getAbsolutePath().replace(scatterSample.getRootPath(), "");
//            addEntry(relativePath + File.separator, dir, scatterSample);
//            return;
//        }for (String file : dir) {File f = new File(file);if (!f.isDirectory()){relativePath = f.getParent().replace(scatterSample.getRootPaths(), "");addEntry(relativePath + File.separator + f.getName(), f, scatterSample);}}}public void createZipFile(final List<String> rootPaths, final File result) throws Exception {File dstFolder = new File(result.getParent());if (!dstFolder.isDirectory()) {dstFolder.mkdirs();}final HighEffiCompressZip scatterSample = new HighEffiCompressZip("zip");compressCurrentDirectory(rootPaths, scatterSample);final ZipArchiveOutputStream zipArchiveOutputStream = new ZipArchiveOutputStream(result);scatterSample.writeTo(zipArchiveOutputStream);zipArchiveOutputStream.close();}}public class HighEffiCompressZip {private String rootPaths;ParallelScatterZipCreator scatterZipCreator = new ParallelScatterZipCreator();// ParallelScatterZipCreator api says:// 注意这个类不保证写入到输出文件的顺序。需要保持特定顺序的(manifests,文件夹)必须使用这个类的客户类进行处理// 通常的做法是 在调用这个类的writeTo方法前把这些东西写入到ZipArchiveOutputStreamScatterZipOutputStream dirs = ScatterZipOutputStream.fileBased(File.createTempFile("whatever-preffix", ".whatever"));public HighEffiCompressZip(String rootPaths) throws IOException {this.rootPaths = rootPaths;}public HighEffiCompressZip() throws IOException {}public void addEntry(final ZipArchiveEntry zipArchiveEntry, final InputStreamSupplier streamSupplier)throws IOException {if (zipArchiveEntry.isDirectory() && !zipArchiveEntry.isUnixSymlink()) {dirs.addArchiveEntry(ZipArchiveEntryRequest.createZipArchiveEntryRequest(zipArchiveEntry, streamSupplier));} else {scatterZipCreator.addArchiveEntry(zipArchiveEntry, streamSupplier);}}public void writeTo(final ZipArchiveOutputStream zipArchiveOutputStream)throws IOException, ExecutionException, InterruptedException {dirs.writeTo(zipArchiveOutputStream);dirs.close();scatterZipCreator.writeTo(zipArchiveOutputStream);}public String getRootPaths() {return rootPaths;}public void setRootPaths(String rootPath) {this.rootPaths = rootPaths;}}

JAVA 大文件压缩极速下载相关推荐

  1. Java把文件压缩然后下载

    一边压缩一边下载,前端写法可以参考Java通过流下载文件以及相关优化 response.setContentType("application/octet-stream");res ...

  2. Java多文件压缩下载解决方案

    Java多文件压缩下载解决方案 需求: 会员运营平台经过改版后页面增加了许多全部下载链接,上周上线比较仓促,全部下载是一个直接下载ZIP压缩文件的链接,每个ZIP压缩文件都是由公司运营人员将页面需要下 ...

  3. Java实现FTP批量大文件上传下载

    用Java实现FTP批量大文件上传下载 <iframe id="I0_1416224567509" style="margin: 0px; padding: 0px ...

  4. Java将一个文件夹下多个文件压缩并下载(工作案例)

    Java将一个文件下多个文件压缩并下载,文件夹目录如下: 每个文件下都有文件,要求实现将文件夹"A2023001_检查"压缩成"A2023001.zip",如下 ...

  5. 使用java iTest实现PDF大文件压缩——将文件过大的图片PDF文件压缩成小一些的图片PDF文件

    一.需求 项目中需要将文件大小过大的PDF文件,压缩成小PDF文件.通过iText的API,可以实现此需求.在保证文件不失真的前提下,将PDF大文件压缩成小文件. 二.代码 import com.it ...

  6. java大文件读写操作

    转载自:http://blog.csdn.net/akon_vm/article/details/7429245 RandomAccessFile RandomAccessFile是用来访问那些保存数 ...

  7. centos nfs java_CentOS下安装配置NFS并通过Java进行文件上传下载

    1:安装NFS (1)安装 yum install nfs-utils rpcbind (2)启动rpcbind服务 systemctl restart rpcbind.service 查看服务状态 ...

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

      程序员在做web等项目的时候,往往都需要添加文件上传.下载.删除的功能,有时是单文件,有时多文件批量 操作,而这些功能的代码程序员可以自己收藏起来当成工具使用,这样,程序员在进行程序设计的时候就会 ...

  9. JAVA大文件上传断点续传解决方案

    JAVA大文件上传断点续传解决方案 参考文章: (1)JAVA大文件上传断点续传解决方案 (2)https://www.cnblogs.com/songsu/p/11834425.html (3)ht ...

  10. kettle将多个文件压缩_如何使用WinRAR将一个大文件压缩成多个小的压缩包

    目录 1.使用WinRAR将一个大文件压缩成多个小的压缩包 2.使用WinRAR将多个小的压缩包,解压/合并成一个大文件 3.结尾 / 在现实生活中,受文件大小的限制,在传输的过程往往出现困难,如:邮 ...

最新文章

  1. C语言 一个字符常量占几个字节
  2. 解决延迟有 Wi-Fi 6 就够了!
  3. ieee期刊_论文绘图神器来了:哈佛博士后开源,一行代码绘制不同期刊格式图表...
  4. NodeJs-- 新建项目实例
  5. jquery表单验证
  6. c malloc结构体_9.8 C++动态分配 | 存放结构体变量
  7. 牛客网编程题06--取近似值
  8. URL 编码和解码工具
  9. sap系统和服务器的关系,erp系统和sap系统的区别
  10. 29个最酷的Firefox About:Config配置参数
  11. java计算机毕业设计用户行为自动化书籍推荐系统MyBatis+系统+LW文档+源码+调试部署
  12. 如何做好会员管理与维护?
  13. 三重邪骨手机版怎么登录服务器未响应,三重邪骨困难版
  14. 嵌入式工程师学习第二天
  15. 牛客练习赛 43 CTachibana Kanade Loves Review 最小生成树(Java版失败)
  16. 蛮牛手册之working in unity
  17. C++ Primer 13-15
  18. zigbee室内定位
  19. SIT与UAT的区别
  20. C语言课程设计——学生证管理系统

热门文章

  1. 微信推送封面尺寸_一篇公众号推文如何设置两张封面图?
  2. 《系统集成项目管理》第九章 项目成本管理
  3. hive hql 交差并集 练习
  4. python操作autocad_利用python控制Autocad:pyautocad方式
  5. nginx打开网页报错
  6. array函数python_python中如何使用numpy.array函数创建数组?
  7. book mac pro怎么重装系统_Macbook Pro 2011完全重装系统
  8. 国内硕士申请加拿大计算机博士难度,【经验分享】如何申请加拿大硕士研究生或者博士?...
  9. 如何把照片转成pdf文件,支持合并转换
  10. 分享可用的谷歌学术(google scholar) hosts