打包多个文件(夹)
@Test
public void test6() throws IOException {
zipCompress("/Users/quyuantao/Documents/资料,/Users/quyuantao/Documents/项目",
"/Users/quyuantao/Desktop/资料汇总.zip");
}
public static void zipCompress(String input, String output) throws IOException {
ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(output));
BufferedOutputStream bos = new BufferedOutputStream(zos);
String[] paths = input.split(",");
for (String path : paths) {
File file = new File(path);
compress(zos, bos, file, null);
}
bos.close();
}
public static void compress(ZipOutputStream zos,
BufferedOutputStream bos,
File input,
String name) throws IOException {
if (name == null) {
name = input.getName();
}
if (input.isDirectory()) {
File[] listFiles = input.listFiles();
if (listFiles == null || listFiles.length == 0) {
zos.putNextEntry(new ZipEntry(name + File.separator));
} else {
for (File file : listFiles) {
compress(zos, bos, file, name + File.separator + file.getName());
}
}
} else {
zos.putNextEntry(new ZipEntry(name));
FileInputStream fis = new FileInputStream(input);
BufferedInputStream bis = new BufferedInputStream(fis);
byte[] bytes = new byte[1024];
int len;
while ((len = bis.read(bytes)) != -1) {
bos.write(bytes, 0, len);
}
bis.close();
bos.flush();
}
}
解压缩
@Test
public void test7() throws IOException {
zipUnCompress("/Users/quyuantao/Desktop/资料汇总.zip", "/Users/quyuantao/Desktop/资料汇总");
}
public static void zipUnCompress(String inputZip, String destFilePath) throws IOException {
File srcZip = new File(inputZip);
if (!srcZip.exists()) {
throw new FileNotFoundException("未找到压缩包 " + inputZip);
}
try (ZipInputStream zis = new ZipInputStream(new FileInputStream(srcZip))) {
ZipEntry zipEntry;
while ((zipEntry = zis.getNextEntry()) != null) {
if (!zipEntry.isDirectory()) {
File file = new File(destFilePath, zipEntry.getName());
if (!file.exists()) {
boolean parDir = new File(file.getParent()).mkdirs();
}
try (BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file))) {
byte[] bytes = new byte[1024];
int len;
while ((len = zis.read(bytes)) != -1) {
bos.write(bytes, 0, len);
}
}
}
}
}
}