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

最新文章

  1. iOS--NSBundle理解
  2. Ember.js之动态创建模型
  3. JAVA_HOME环境变量失效的解决办法
  4. PHP面向对象学习一
  5. MongoDB学习(四)客户端工具备份数据库
  6. JQuery Pagination 分页插件 增加了首页尾页以及跳转功能
  7. 修练8年C++面向对象程序设计之体会
  8. linux 内核---------董昊 ( Robin Dong ) and OenHan
  9. Linux下安装Python pip
  10. JS判断手机端和PC端自动跳转
  11. HTML和XHTML区别
  12. node 创建
  13. 迅为iTOP-4418/6818开发板-驱动-实现GPIO扩展
  14. (转)sql 违反了 PRIMARY KEY 约束,不能在对象 中插入重复键
  15. 数据库 -- mysql支持的数据类型
  16. Android 获取Activity当前view
  17. Linux内核分析——第七章 链接
  18. Bootstrap3.0学习第二轮(栅格系统原理)
  19. leaflet入门(一)示例
  20. keepalived启动不成功,状态一直是inactive(dead) 的解决办法以及keepalived高版本没有rc.d目录,虚拟VIP无法访问问题

热门文章

  1. Android开发中UI相关的问题总结
  2. 【转载】salesforce 零基础开发入门学习(五)异步进程介绍与数据批处理Batchable
  3. linux命令启动关闭firewalld防火墙,添加端口
  4. 线段树lazy模板 luogu3372
  5. [Mac][Python][Jupyter Notebook]安装配置和使用
  6. centos下关闭自动锁屏
  7. Disable trigger to avoid the ID is auto-updated
  8. python 2.7安装pygame报错解决办法pygame-1.9.4-cp27-cp27m-win_amd64.whl is not a supported wheel on this platform.
  9. linux实操_进程管理
  10. Oracle不足补零函数