java處理文件時,有時候需要對文件進行zip壓縮操作,可以使用java自帶的api實現解壓縮功能。
1.壓縮
1.1 將文件壓縮到指定的zip文件
/**
* 壓縮多個文件成一個zip文件
*
* @param srcFiles:源文件列表
* @param destZipFile:壓縮后的文件
*/
public static void toZip(File[] srcFiles, File destZipFile) {
byte[] buf = new byte[1024];
try {
// ZipOutputStream類:完成文件或文件夾的壓縮
ZipOutputStream out = new ZipOutputStream(new FileOutputStream(destZipFile));
for (int i = 0; i < srcFiles.length; i++) {
FileInputStream in = new FileInputStream(srcFiles[i]);
// 給列表中的文件單獨命名
out.putNextEntry(new ZipEntry(srcFiles[i].getName()));
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
out.closeEntry();
in.close();
}
out.close();
log.info("壓縮完成.");
} catch (Exception e) {
log.error("壓縮出錯,", e);
}
}
1.2 通過瀏覽器響應下載文件
- 方式一
/**
* 壓縮成ZIP 方法1
*
* @param srcDir 壓縮文件夾路徑
* @param out 壓縮文件輸出流
* @param keepDirStructure 是否保留原來的目錄結構,true:保留目錄結構;
* false:所有文件跑到壓縮包根目錄下
* (注意:不保留目錄結構可能會出現同名文件,會壓縮失敗)
* @throws RuntimeException 壓縮失敗會拋出運行時異常
*/
public static void toZip(String srcDir, OutputStream out, boolean keepDirStructure) {
StopWatch stopWatch = new StopWatch();
stopWatch.start("toZip-1");
ZipOutputStream zos = null;
try {
zos = new ZipOutputStream(out);
File sourceFile = new File(srcDir);
compress(sourceFile, zos, sourceFile.getName(), keepDirStructure);
} catch (Exception e) {
log.error("壓縮zip出錯,", e);
throw new RuntimeException("壓縮zip出錯");
} finally {
close(zos);
}
stopWatch.stop();
log.info("toZip-1 共耗時:{}", stopWatch.getTotalTimeMillis());
}
- 方式二
/**
* 壓縮成ZIP 方法2
*
* @param srcFiles 需要壓縮的文件列表
* @param out 壓縮文件輸出流
* @throws RuntimeException 壓縮失敗會拋出運行時異常
*/
public static void toZip(List<File> srcFiles, OutputStream out) throws RuntimeException {
StopWatch stopWatch = new StopWatch();
stopWatch.start("toZip-2");
ZipOutputStream zos = null;
try {
zos = new ZipOutputStream(out);
for (File sourceFile : srcFiles) {
byte[] buf = new byte[BUFFER_SIZE];
zos.putNextEntry(new ZipEntry(sourceFile.getName()));
int len;
FileInputStream in = new FileInputStream(sourceFile);
while ((len = in.read(buf)) != -1) {
zos.write(buf, 0, len);
}
zos.closeEntry();
in.close();
}
} catch (Exception e) {
log.error("壓縮zip出錯,", e);
throw new RuntimeException("壓縮zip出錯");
} finally {
close(zos);
}
stopWatch.stop();
log.info("toZip-2 共耗時:{}", stopWatch.getTotalTimeMillis());
}
2.解壓
/**
* 解壓文件
*
* @param zipFile:需要解壓縮的文件
* @param descDir:解壓后的目標目錄
*/
public static void unZipFiles(File zipFile, String descDir) throws IOException {
File destFile = new File(descDir);
if (!destFile.exists()) {
destFile.mkdirs();
}
// 解決zip文件中有中文目錄或者中文文件
ZipFile zip = new ZipFile(zipFile, Charset.forName("GBK"));
for (Enumeration entries = zip.entries(); entries.hasMoreElements(); ) {
ZipEntry entry = (ZipEntry) entries.nextElement();
InputStream in = zip.getInputStream(entry);
String curEntryName = entry.getName();
// 判斷文件名路徑是否存在文件夾
int endIndex = curEntryName.lastIndexOf('/');
// 替換
String outPath = (descDir + curEntryName).replaceAll("\\*", "/");
if (endIndex != -1) {
File file = new File(outPath.substring(0, outPath.lastIndexOf("/")));
if (!file.exists()) {
file.mkdirs();
}
}
// 判斷文件全路徑是否為文件夾,如果是上面已經上傳,不需要解壓
File outFile = new File(outPath);
if (outFile.isDirectory()) {
continue;
}
OutputStream out = new FileOutputStream(outPath);
byte[] buf1 = new byte[1024];
int len;
while ((len = in.read(buf1)) > 0) {
out.write(buf1, 0, len);
}
in.close();
out.close();
}
log.info("解壓{}成功", zipFile.getName());
}
3. 測試
package com.common.util.zip.controller; import com.common.util.zip.ZipUtils; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.StringUtils; import org.apache.shiro.util.Assert; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.File; import java.io.IOException; import java.net.URLEncoder; import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; import java.util.Arrays; import java.util.List; /** * @author * @Describe 功能描述 * @date */ @RestController @Slf4j(topic = "ZipController") public class ZipController { String srcDir = "C:\\Users\\kinson\\Desktop\\zipTest"; String desDir = "C:\\Users\\kinson\\Desktop\\unzip\\"; String desZipFilename = "C:\\Users\\kinson\\Desktop\\zipTest\\dest.zip"; String desZipFilePath = "C:\\Users\\kinson\\Desktop\\"; @RequestMapping(value = "toZip") public void toZip(HttpServletRequest request, HttpServletResponse response, String type) throws IOException { if (StringUtils.isEmpty(type)) { // 瀏覽器響應返回 response.reset(); // 設置response的header,response為HttpServletResponse接收輸出流 response.setContentType("application/zip"); String zipFileName = "zipFile-" + LocalDateTime.now().format(DateTimeFormatter.ofPattern( "yyyyMMddHHmmss")) + ".zip"; response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(zipFileName, "UTF-8" )); ZipUtils.toZip(srcDir, response.getOutputStream(), true); } else if (StringUtils.equals(type, "2")) { // 瀏覽器響應返回2 File file = new File(srcDir); if (file.isDirectory() && file.listFiles().length > 0) { File[] files = file.listFiles(); List<File> fileList = Arrays.asList(files); response.reset(); // 設置response的header,response為HttpServletResponse接收輸出流 response.setContentType("application/zip"); String zipFileName = "zipFile2-" + LocalDateTime.now().format(DateTimeFormatter.ofPattern( "yyyyMMddHHmmss")) + ".zip"; response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(zipFileName, "UTF-8" )); ZipUtils.toZip(fileList, response.getOutputStream()); } } else if (StringUtils.equals(type, "3")) { // 指定目錄 File file = new File(srcDir); File desZipFile = new File(desZipFilename); if (file.isDirectory() && file.listFiles().length > 0) { File[] files = file.listFiles(); ZipUtils.toZip(files, desZipFile); } } else { log.info("type is {}", type); } } @RequestMapping(value = "unZip") public void unZip(String zipFilename) throws IOException { Assert.isTrue(StringUtils.isNotEmpty(StringUtils.trim(zipFilename))); File file = new File(desZipFilePath + zipFilename + ".zip"); ZipUtils.unZipFiles(file, desDir); } }