java使用7z對文件壓縮可以使文件大小被壓縮的很小,便於對文件的歸檔處理,使用apache的commons-compress可以實現文件的7z解壓縮功能
1.壓縮
/**
* 7z文件壓縮
*
* @param inputFile 待壓縮文件夾/文件名
* @param outputFile 生成的壓縮包名字
*/
public static void compress7z(String inputFile, String outputFile) {
log.info("開始7z壓縮本地路徑{}的相關日志到{}壓縮文件中", inputFile, outputFile);
StopWatch watch = new StopWatch();
watch.start("7z壓縮");
SevenZOutputFile outArchive = null;
try {
File input = new File(inputFile);
if (!input.exists()) {
throw new RuntimeException(input.getPath() + "待壓縮文件不存在");
}
File output = new File(outputFile);
outArchive = new SevenZOutputFile(output);
// 遞歸壓縮
compress(outArchive, input, null);
} catch (Exception e) {
log.error("7z文件壓縮出現異常源路徑{},目標路徑{}", inputFile, outputFile, e);
throw new RuntimeException("7z文件壓縮出現異常");
} finally {
// 關閉
closeSevenZOutputFile(outArchive);
}
watch.stop();
log.info("結束7z壓縮本地路徑{}的相關日志到{}壓縮文件中,耗時{}ms", inputFile, outputFile, watch.getTotalTimeMillis());
}
2.解壓
/**
* 7z文件解壓
*
* @param inputFile 待解壓文件名
* @param destDirPath 解壓路徑
*/
public static void unCompress7z(String inputFile, String destDirPath) throws Exception {
StopWatch watch = new StopWatch();
watch.start("7z解縮");
// 獲取當前壓縮文件
File srcFile = new File(inputFile);
// 判斷源文件是否存在
if (!srcFile.exists()) {
throw new Exception(srcFile.getPath() + "所指文件不存在");
}
// 開始解壓
SevenZFile zIn = new SevenZFile(srcFile);
SevenZArchiveEntry entry = null;
File file = null;
while ((entry = zIn.getNextEntry()) != null) {
if (!entry.isDirectory()) {
file = new File(destDirPath, entry.getName());
if (!file.exists()) {
// 創建此文件的上級目錄
new File(file.getParent()).mkdirs();
}
OutputStream out = new FileOutputStream(file);
BufferedOutputStream bos = new BufferedOutputStream(out);
int len = -1;
byte[] buf = new byte[1024];
while ((len = zIn.read(buf)) != -1) {
bos.write(buf, 0, len);
}
// 關流順序,先打開的后關閉
bos.close();
out.close();
}
}
watch.stop();
log.info("結束7z解壓,耗時{}ms", watch.getTotalTimeMillis());
}
3.測試
package com.common.util.sevenz.controller; import com.common.util.sevenz.SevenZipUtil; import org.apache.commons.lang3.StringUtils; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import javax.servlet.ServletOutputStream; import javax.servlet.http.HttpServletResponse; import java.io.*; import java.net.URLEncoder; import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; /** * @author * @Describe 功能描述 * @date */ @RestController public class SevenzTestController { String srcPath = "C:\\Users\\kinson\\Desktop\\7zTest"; String dest7zFilePath = "C:\\Users\\kinson\\Desktop\\7zTest.7z"; String destPath = "C:\\Users\\kinson\\Desktop\\un7z"; @RequestMapping(value = "compress7z") public void compress7z(HttpServletResponse response, String type) throws IOException { if (StringUtils.isEmpty(type)) { // 瀏覽器響應 // 瀏覽器響應返回 response.reset(); // 設置response的header,response為HttpServletResponse接收輸出流 response.setContentType("application/octet-stream"); String sevenzFileName = "7zFile-" + LocalDateTime.now().format(DateTimeFormatter.ofPattern( "yyyyMMddHHmmss")) + ".7z"; response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(sevenzFileName, "UTF-8")); // 壓縮為7z SevenZipUtil.compress7z(srcPath, dest7zFilePath); // 將壓縮好的7z響應給瀏覽器 File file = new File(dest7zFilePath); if (null != file && file.isFile()) { ServletOutputStream os = response.getOutputStream(); FileInputStream fis = new FileInputStream(file); BufferedInputStream bis = new BufferedInputStream(fis); int len = -1; // 將源文件寫入到輸出流 byte[] buf = new byte[1024]; while ((len = bis.read(buf)) != -1) { os.write(buf, 0, len); } bis.close(); fis.close(); os.close(); } } else { // 寫到目標文件 SevenZipUtil.compress7z(srcPath, dest7zFilePath); } } @RequestMapping(value = "unCompress7z") public void unCompress7z() throws Exception { // 解壓 SevenZipUtil.unCompress7z(dest7zFilePath, destPath); } }