Zip 压缩工具类,不支持压缩空文件夹。

简单版

import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.file.*;
import java.nio.file.attribute.BasicFileAttributes;
import java.time.Instant;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream; public class ZipUtil {
public static void main(String[] args) {
zipCompression("D:\\123.zip", "D:\\123", "D:\\456", "D:\\er4.zip");
} static void zipCompression(String zipPath, String... paths) {
Path[] ps = new Path[paths.length];
for (int i = 0; i < paths.length; i++) {
ps[i] = Paths.get(paths[i]);
}
zipCompression(Paths.get(zipPath), ps);
} static void zipCompression(Path zipPath, Path... paths) {
long beginTime = Instant.now().toEpochMilli();
try (ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(zipPath.toFile()))) {
for (Path path : paths) {
Files.walkFileTree(path, new SimpleFileVisitor<Path>() {
@Override // 访问一个文件
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
zos.putNextEntry(new ZipEntry(file.toString().replace(path.getParent().toString(), "")));
Files.copy(file, zos);
zos.closeEntry();
return FileVisitResult.CONTINUE;
}
});
}
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("耗时:" + (Instant.now().toEpochMilli() - beginTime));
}
}

内存映射+管道+异步线程版,效率似乎没有什改变。。。。。。

import java.io.*;
import java.nio.ByteBuffer;
import java.nio.MappedByteBuffer;
import java.nio.channels.Channels;
import java.nio.channels.FileChannel;
import java.nio.channels.Pipe;
import java.nio.channels.WritableByteChannel;
import java.nio.file.*;
import java.nio.file.attribute.BasicFileAttributes;
import java.time.Instant;
import java.util.concurrent.CompletableFuture;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream; public class ZipUtil {
public static void main(String[] args) {
zipCompression("D:\\123.zip", "D:\\123", "D:\\456", "D:\\er4.zip");
} static void zipCompression(String zipPath, String... paths) {
Path[] ps = new Path[paths.length];
for (int i = 0; i < paths.length; i++) {
ps[i] = Paths.get(paths[i]);
}
zipCompression(Paths.get(zipPath), ps);
} static void zipCompression(Path zipPath, Path... paths) {
long beginTime = Instant.now().toEpochMilli();
try (FileOutputStream fileOutputStream = new FileOutputStream(zipPath.toFile());
WritableByteChannel out = Channels.newChannel(fileOutputStream)) {
Pipe pipe = Pipe.open();
// 异步任务往通道中塞入数据
CompletableFuture.runAsync(() -> runCompressionTask(pipe, paths));
// 读取通道中数据
Pipe.SourceChannel source = pipe.source(); ByteBuffer buffer = ByteBuffer.allocate(2048);
// ByteBuffer buffer = ByteBuffer.allocateDirect(2048);
while (source.read(buffer) >= 0) {
buffer.flip();
out.write(buffer);
buffer.clear();
}
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("耗时:" + (Instant.now().toEpochMilli() - beginTime));
} // 异步任务
public static void runCompressionTask(Pipe pipe, Path... paths) {
try (Pipe.SinkChannel sink = pipe.sink();
OutputStream os = Channels.newOutputStream(sink);
ZipOutputStream zos = new ZipOutputStream(os);
WritableByteChannel out = Channels.newChannel(zos)) { for (Path path : paths) {
Files.walkFileTree(path, new SimpleFileVisitor<Path>() {
@Override // 访问一个目录
public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {
if (dir.toFile().list().length == 0) {
// 无法打包空文件夹
// zos.putNextEntry(new ZipEntry(dir.toString().replace(path.getParent().toString(), "") + File.separator));
// System.out.println(dir.toString().replace(path.getParent().toString(), "") + File.separator);
// zos.closeEntry();
}
return FileVisitResult.CONTINUE;
} @Override // 访问一个文件
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
zos.putNextEntry(new ZipEntry(file.toString().replace(path.getParent().toString(), ""))); MappedByteBuffer mappedByteBuffer = new RandomAccessFile(file.toFile(), "r").getChannel().map(FileChannel.MapMode.READ_ONLY, 0, attrs.size());
out.write(mappedByteBuffer); // FileChannel fileChannel = new FileInputStream(file.toFile()).getChannel();
// fileChannel.transferTo(0, fileChannel.size(), out);
// fileChannel.close(); zos.closeEntry();
return FileVisitResult.CONTINUE;
}
});
}
zos.finish();
} catch (IOException e) {
e.printStackTrace();
}
}
}

用到了 NIO 相关特性


https://juejin.im/post/5d5626cdf265da03a65312be

https://www.cnblogs.com/jhxxb/p/11272727.html

https://www.cnblogs.com/jhxxb/p/11303947.html

Java-ZipUtil的更多相关文章

  1. Spark案例分析

    一.需求:计算网页访问量前三名 import org.apache.spark.rdd.RDD import org.apache.spark.{SparkConf, SparkContext} /* ...

  2. java 解压缩Zip文件 ziputil

    package com.lanyuan.assembly.util; import java.io.BufferedOutputStream;import java.io.File;import ja ...

  3. 【转】Java压缩和解压文件工具类ZipUtil

    特别提示:本人博客部分有参考网络其他博客,但均是本人亲手编写过并验证通过.如发现博客有错误,请及时提出以免误导其他人,谢谢!欢迎转载,但记得标明文章出处:http://www.cnblogs.com/ ...

  4. Java实现压缩与解压缩

    import java.io.*; import java.util.*; import java.util.zip.ZipOutputStream; import java.util.zip.Zip ...

  5. Java导出excel

    一.介绍 常常有客户这样子要求:你要把我们的报表直接用Excel打开(电信系统.银行系统).或者是:我们已经习惯用Excel打印.这样在我们实际的开发中,很多时候需要实现导入.导出Excel的应用. ...

  6. Java 基础【12】 压缩与解压缩

    Java.util.zip 提供用于读写标准 ZIP 和 GZIP 文件格式的类. 还包括使用 DEFLATE 压缩算法(用于 ZIP 和 GZIP 文件格式)对数据进行压缩和解压缩的类. 依赖 Jd ...

  7. 原生java 压缩解压zip文件

    import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.File; import ...

  8. Java 压缩字符串

    1.引言 最近在做项目中,平台提供一个http服务给其他系统调用,然后我接收到其他系统的json格式的报文后去解析,然后用拿到的数据去调用corba服务,我再把corba的返回值封装完成json字符串 ...

  9. java中常用的工具类(二)

    下面继续分享java中常用的一些工具类,希望给大家带来帮助! 1.FtpUtil           Java   1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 ...

  10. Java操作zip压缩和解压缩文件工具类

    需要用到ant.jar(这里使用的是ant-1.6.5.jar) import java.io.File; import java.io.FileInputStream; import java.io ...

随机推荐

  1. 【Salesforce】入门篇

    Salesforce.com 一开始是一个云端的销售自动化(Sales Force Automation, SFA)以及客户关系管理工具(Customer Relationship Managemen ...

  2. gitlab自动化部署CI案例

    参考: https://blog.csdn.net/hxpjava1/article/details/78514999   (简单操作) https://blog.csdn.net/wh211212/ ...

  3. 案例:selenium实现登录百度(如有验证码,需要手动输入)

    func.py https://www.cnblogs.com/andy9468/p/10899508.html baidu_login.py中(如有验证码,需要手动输入) # 导入webdriver ...

  4. 【leetcode】610. Triangle Judgement

    原题 A pupil Tim gets homework to identify whether three line segments could possibly form a triangle. ...

  5. Mount 使用方法

    NAME mount - 挂载文件系统 SYNOPSIS 总览 mount [-lhV] mount -a [-fFnrsvw] [-t vfstype] [-O optlist] mount [-f ...

  6. linux 基础8-shell script

    1. 什么是shell script 1.1 介绍: 什么是 shell script (程序化脚本) 呢?就字面上的意义,我们将他分为两部份. 在『 shell 』部分,我们在bash当中已经提过了 ...

  7. [Selenium3+python3.6]自动化测试2-入门

    参考http://www.cnblogs.com/yoyoketang/p/6123890.html #coding=utf-8 #Import webdriver time module from ...

  8. MyEclipse设置java文件每行字符数

    window->preferences->java->code style->formatter->edit->line wrapping->maximum ...

  9. C C++输出格式 <转载>仅用于个人

    转载链接:C++ C C语言输出格式总结 1 一般格式    printf(格式控制,输出表列)    例如:printf("i=%d,ch=%c\n",i,ch);    说明: ...

  10. Iterator 和 ListIterator 有什么区别?(未完成)

    Iterator 和 ListIterator 有什么区别?(未完成)