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 零基础开发入门学习(四)多表关联下的SOQL以及表字段Data type详解

    salesforce 零基础开发入门学习(四)多表关联下的SOQL以及表字段Data type详解   建立好的数据表在数据库中查看有很多方式,本人目前采用以下两种方式查看数据表. 1.采用schem ...

  2. iOS8中UIActionSheet弹出UIImagePickerController异常处理

    iOS8之后,UIActionSheet改父于UIAlertController.带来了一丢丢兼容性的问题. 比如在弹出的actionsheet中选择从相册选择图片或者拍照,之后弹出UIImagePi ...

  3. MySQL之字符函数

    MySql中提供一些函数对我们的开发有很多的帮助,下面就把MysQL提供的一些常用函数整理下,首先是字符处理函数: 1.CONCAT() 用法:字符串链接函数,将字符串字段连结在一块 举例: sele ...

  4. 用一个N点复序列的FFT同时计算两个N点实序列离散傅里叶变换

    一.功能 用一个\(N\)点复序列快速傅立叶变换算法来同时计算两个\(N\)点实序列的离散傅立叶变换. 二.方法简介 假设\(x(n)\)与\(y(n)\)都是长度为\(N\)的实序列,为计算其离散傅 ...

  5. Go语言—— Array,Slice,Map 和 Set

    转自:https://se77en.cc/ Array(数组) 内部机制 在 Go 语言中数组是固定长度的数据类型,它包含相同类型的连续的元素,这些元素可以是内建类型,像数字和字符串,也可以是结构类型 ...

  6. Windows10关闭自动更新方法

    你在为windows10自动更新而烦恼吗?下面教你一招如何关闭自动更新

  7. C# EPPlus 导出Excel

    一.Excel导出帮助类 /*引用NuGet包 EPPlus*/ /// <summary> /// Excel导出帮助类 /// </summary> public clas ...

  8. linux如何查看所有的用户和组信息

    [步骤一]cat /etc/passwd cat /etc/passwd查看所有的用户信息,详情如下图 [步骤二]cat /etc/passwd|grep 用户名 cat /etc/passwd|gr ...

  9. 文件传输server.py

    用于局域网机器之间临时互传文件,修复了中文乱码问题 # -*- coding: utf-8 -*- #!/usr/bin/env python3 """Simple HT ...

  10. 在多语句事务内不允许使用 CREATE DATABASE 语句。

    方法一:create database [ 项目名称] 方法二:update-database -verbose