jar坐標:
<dependency> <groupId>org.apache.ant</groupId> <artifactId>ant</artifactId> <version>1.10.5</version> </dependency>
話不多說,直接上代碼
package com.demo.student.util; import org.apache.tools.zip.ZipEntry; import org.apache.tools.zip.ZipOutputStream; import java.io.*; /** * 生成壓縮文件 (zip,rar 格式) */ public class CompressUtil { /** * @param path 要壓縮的文件路徑 * @param format 生成的格式(zip、rar)d */ public static void generateFile(String path, String format) throws Exception { File file = new File(path); // 壓縮文件的路徑不存在 if (!file.exists()) { throw new Exception("路徑 " + path + " 不存在文件,無法進行壓縮..."); } // 用於存放壓縮文件的文件夾 String generateFile = file.getParent() + File.separator +"CompressFile"; File compress = new File(generateFile); // 如果文件夾不存在,進行創建 if( !compress.exists() ){ compress.mkdirs(); } // 目的壓縮文件 String generateFileName = compress.getAbsolutePath() + File.separator + "AAA" + file.getName() + "." + format; // 輸入流 表示從一個源讀取數據 // 輸出流 表示向一個目標寫入數據 // 輸出流 FileOutputStream outputStream = new FileOutputStream(generateFileName); // 壓縮輸出流 ZipOutputStream zipOutputStream = new ZipOutputStream(new BufferedOutputStream(outputStream)); generateFile(zipOutputStream,file,""); System.out.println("源文件位置:" + file.getAbsolutePath() + ",目的壓縮文件生成位置:" + generateFileName); // 關閉 輸出流 zipOutputStream.close(); } /** * @param out 輸出流 * @param file 目標文件 * @param dir 文件夾 * @throws Exception */ private static void generateFile(ZipOutputStream out, File file, String dir) throws Exception { // 當前的是文件夾,則進行一步處理 if (file.isDirectory()) { //得到文件列表信息 File[] files = file.listFiles(); //將文件夾添加到下一級打包目錄 out.putNextEntry(new ZipEntry(dir + "/")); dir = dir.length() == 0 ? "" : dir + "/"; //循環將文件夾中的文件打包 for (int i = 0; i < files.length; i++) { generateFile(out, files[i], dir + files[i].getName()); } } else { // 當前是文件 // 輸入流 FileInputStream inputStream = new FileInputStream(file); // 標記要打包的條目 out.putNextEntry(new ZipEntry(dir)); // 進行寫操作 int len = 0; byte[] bytes = new byte[1024]; while ((len = inputStream.read(bytes)) > 0) { out.write(bytes, 0, len); } // 關閉輸入流 inputStream.close(); } } // 測試 public static void main(String[] args) { String path = ""; String format = "rar"; try { generateFile(path, format); } catch (Exception e) { e.printStackTrace(); System.out.println(e.getMessage()); } } }
結果圖:
壓縮整個文件
/** * 遞歸壓縮文件 * @param output ZipOutputStream 對象流 * @param file 壓縮的目標文件流 * @param childPath 條目目錄 */ private static void zip(ZipOutputStream output,File file,String childPath){ FileInputStream input = null; try { // 文件為目錄 if (file.isDirectory()) { // 得到當前目錄里面的文件列表 File list[] = file.listFiles(); childPath = childPath + (childPath.length() == 0 ? "" : "/") + file.getName(); // 循環遞歸壓縮每個文件 for (File f : list) { zip(output, f, childPath); } } else { // 壓縮文件 childPath = (childPath.length() == 0 ? "" : childPath + "/") + file.getName(); output.putNextEntry(new ZipEntry(childPath)); input = new FileInputStream(file); int readLen = 0; byte[] buffer = new byte[1024 * 8]; while ((readLen = input.read(buffer, 0, 1024 * 8)) != -1) { output.write(buffer, 0, readLen); } } } catch (Exception ex) { ex.printStackTrace(); } finally { // 關閉流 if (input != null) { try { input.close(); } catch (IOException ex) { ex.printStackTrace(); } } } } /** * 壓縮文件(文件夾) * @param path 目標文件流 * @param format zip 格式 | rar 格式 * @throws Exception */ public static String zipFile(File path,String format) throws Exception { String generatePath = ""; if( path.isDirectory() ){ generatePath = path.getParent().endsWith("/") == false ? path.getParent() + File.separator + path.getName() + "." + format: path.getParent() + path.getName() + "." + format; }else { generatePath = path.getParent().endsWith("/") == false ? path.getParent() + File.separator : path.getParent(); generatePath += path.getName().substring(0,path.getName().lastIndexOf(".")) + "." + format; } // 輸出流 FileOutputStream outputStream = new FileOutputStream( generatePath ); // 壓縮輸出流 ZipOutputStream out = new ZipOutputStream(new BufferedOutputStream(outputStream)); zip(out, path,""); out.flush(); out.close(); return generatePath; }
使用
// 使用例子 public static void main(String[] args) { String path = "F:/test"; String format = "zip"; try { System.out.println(zipFile(new File(path),format)); } catch (Exception e) { e.printStackTrace(); System.out.println(e.getMessage()); } }
解壓
/** * * @param sourceZip 待解壓文件路徑 * @param destDir 解壓到的路徑 */ public static String unZip(String sourceZip, String destDir) { //保證文件夾路徑最后是"/"或者"\" if( !destDir.endsWith("/") ){ destDir += File.separator; } String newDir = ""; File sourceFile = new File(sourceZip); newDir = sourceFile.getName().substring(0,sourceFile.getName().lastIndexOf(".")); File destDirFile = new File(destDir + newDir); Project p = new Project(); Expand e = new Expand(); e.setProject(p); e.setSrc(sourceFile); e.setOverwrite(true); e.setDest(destDirFile); /* ant下的zip工具默認壓縮編碼為UTF-8編碼, 而winRAR軟件壓縮是用的windows默認的GBK或者GB2312編碼 所以解壓縮時要制定編碼格式 */ e.setEncoding("gbk"); e.execute(); return destDirFile.getAbsolutePath(); }