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. SAP WebIDE里UI5应用的隐藏文件project.json

    在SAP WebIDE UI5应用编辑器里的菜单View->Show Hidden files点击后,即可发现项目文件夹下有一个隐藏文件project.json: 内容如下: 这也解释了为什么b ...

  2. TreeMap核心源码实现解析

    TreeMap实现了SotredMap接口,它是有序的集合.而且是一个红黑树结构,每个key-value都作为一个红黑树的节点.如果在调用TreeMap的构造函数时没有指定比较器,则根据key执行自然 ...

  3. GC案例

    FGC----jmap -histo:live导致 线上某服务的老年代配置了CMS,但却在gc.log发现连续Full GC的问题.JVM参数配置如下: -XX:+UseCMSInitiatingOc ...

  4. Flutter——BottomNavigationBar组件(底部导航栏组件)

    BottomNavigationBar常用的属性: 属性名 说明 items List<BottomNavigationBarItem> 底部导航条按钮集合 iconSize icon c ...

  5. asp.net中数据库事务管理

    英文搜索关键字: 文章地址:https://stackoverflow.com/questions/313199/sql-transactions-best-way-to-implement-in-a ...

  6. 2018 CERC 混合博弈

    N堆石子 先手最多拿A个 后手最多拿B个 每次都至少要拿一个 谁先取完谁赢 如果A和B相等直接就是一个bash博弈 如果一个石堆的石子数少于min(A,B) 则是个nim游戏 我们先讨论只有N=1且A ...

  7. sklearn逻辑回归实战

    目录 题目要求 ex2data1.txt处理 方案一:无多项式特征 方案二:引入多项式特征 ex2data2.txt处理 两份数据 ex2data1.txt ex2data2.txt 题目要求 根据学 ...

  8. PhpStudy升级MySQL版本到5.7

    1:备份当前数据库数据. 最好是导成 SQL 文件 2:备份 PhpStudy 下的 MySQL 文件夹.以防升级失败.还可以使用旧版本的数据库 3:下载MySQL5.7.解压.然后放在 PhpStu ...

  9. Python sleep()函数用法:线程睡眠

    如果需要让当前正在执行的线程暂停一段时间,并进入阻塞状态,则可以通过调用 time 模块的 sleep(secs) 函数来实现.该函数可指定一个 secs 参数,用于指定线程阻塞多少秒. 当前线程调用 ...

  10. 模块讲解---os模块,sys模块,json和pickle模块,logging模块

    目录 模块的用法 os模块 常用的功能 sys模块 常用的功能 json和pickle模块 4. logging模块 模块的用法 通过 import 或者from......import...... ...