1,写多个文件到压缩包
import org.apache.tools.zip.ZipEntry;
import org.apache.tools.zip.ZipFile;
import org.apache.tools.zip.ZipOutputStream;
public static void main(String[] args) {
//压缩文件对象
String zipPath = "D:\\download\\files0719.zip";
//需要压缩的文件
String filepath1 = "D:\\download\\yyzz.jpeg";
String filepath2 = "D:\\download\\yyzz1.png";
List<String> files = new ArrayList<>();
files.add(filepath1);
files.add(filepath2);
try (OutputStream os = new BufferedOutputStream(new FileOutputStream(zipPath));
ZipOutputStream zos = new ZipOutputStream(os)) {
byte[] buf = new byte[10240];
int len;
for (int i = 0; i < files.size(); i++) {
File file = new File(files.get(i));
//判断是否是文件数据
if (!file.isFile()) {
continue;
}
zos.putNextEntry(new ZipEntry(file.getName()));
try (BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file))) {
while ((len = bis.read(buf)) > 0) {
zos.write(buf, 0, len);
}
}
}
} catch (Exception e) {
log.info("压缩文件{}失败", JSONUtils.toJSONString(files), e);
throw new BaseException("压缩文件失败", e);
}
}
效果图:
2,压缩文件解压
注意:可以用于递归文件的解压,但是不能对压缩文件里面的压缩文件进行解压
public static void main(String[] args) {
//解压文件
String zipFile = "D:\\download\\filesCompress.zip";
//解压到哪里
String destination = "D:\\download\\unzip";
ArrayList<String> dirList = new ArrayList<>();
try (ZipFile zip = new ZipFile(zipFile, "GBK")) {
//解压对象下有几个对象
Enumeration<ZipEntry> en = zip.getEntries();
byte[] buffer = new byte[8192];
int length = -1;
while (en.hasMoreElements()) {
//获取文件实体
ZipEntry entry = en.nextElement();
//如果是目录
if (entry.isDirectory()) {
dirList.add(entry.getName());
continue;
}
InputStream input = zip.getInputStream(entry);
File file = new File(destination, entry.getName());
//如果文件的父级目录不存在,创建目录
if (!file.getParentFile().exists()) {
file.getParentFile().mkdirs();
}
try(BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file));){
while (true) {
//向缓存区读取文件数据
length = input.read(buffer);
if (length == -1) {
break;
}
bos.write(buffer, 0, length);
}
} finally {
if (input != null) {
try {
input.close();
} catch (IOException e) {
log.error(e.getMessage() == null ? "" : e.getMessage(), e);
}
}
}
}
}catch (Exception e){
e.printStackTrace();
}
}
效果图: