調用ant裡的方法可以完好的實現包括中文在內的zip的壓縮與解壓
具體實現代碼如下:
import java.io.File;import java.io.FileInputStream;import java.io.FileOutputStream;import java.io.IOException;import java.util.logging.Level;import java.util.logging.Logger;import java.util.zip.ZipOutputStream;import org.apache.tools.ant.Project;import org.apache.tools.ant.taskdefs.Expand;import org.apache.tools.zip.ZipEntry;/** * * @author yaohucaizi */public class ZipUtil { /** * * @param file 要壓縮的檔案 * @param zipFile 壓縮檔存放地方 */ public static void zip(File file, File zipFile) { ZipOutputStream outputStream = null; try { outputStream = new ZipOutputStream(new FileOutputStream(zipFile)); zipFile(outputStream, file, ""); if (outputStream != null) { outputStream.flush(); outputStream.close(); } } catch (IOException ex) { Logger.getLogger(ZipUtil.class.getName()).log(Level.SEVERE, null, ex); } finally { try { outputStream.close(); } catch (IOException ex) { Logger.getLogger(ZipUtil.class.getName()).log(Level.SEVERE, null, ex); } } } /** * * @param output ZipOutputStream對象 * @param file 要壓縮的檔案或檔案夾 * @param basePath 條目根目錄 */ private static void zipFile(ZipOutputStream output, File file, String basePath) { FileInputStream input = null; try { // 檔案為目錄 if (file.isDirectory()) { // 得到目前的目錄裡面的檔案清單 File list[] = file.listFiles(); basePath = basePath + (basePath.length() == 0 ? "" : "/") + file.getName(); // 迴圈遞迴壓縮每個檔案 for (File f : list) { zipFile(output, f, basePath); } } else { // 壓縮檔 basePath = (basePath.length() == 0 ? "" : basePath + "/") + file.getName(); // System.out.println(basePath); output.putNextEntry(new ZipEntry(basePath)); 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) { Logger.getLogger(ZipUtil.class.getName()).log(Level.SEVERE, null, ex); } } } } /** * * @param sourceZip 待解壓檔案路徑 * @param destDir 解壓到的路徑 */ public static void unZip(String sourceZip, String destDir) { //保證檔案夾路徑最後是"/"或者"\" char lastChar = destDir.charAt(destDir.length() - 1); if (lastChar != '/' && lastChar != '\\') { destDir += File.separator; } Project p = new Project(); Expand e = new Expand(); e.setProject(p); e.setSrc(new File(sourceZip)); e.setOverwrite(false); e.setDest(new File(destDir)); /* ant下的zip工具預設壓縮編碼為UTF-8編碼, 而winRAR軟體壓縮是用的windows預設的GBK或者GB2312編碼 所以解壓縮時要制定編碼格式 */ e.setEncoding("gbk"); e.execute(); } public static void main(String[] args) { String sourcePath = "C:/model.zip"; String destPath = "C:/test"; unZip(sourcePath, destPath); zip(new File("C:/test/model"), new File("d:/model.zip")); }}
以上代碼即可實現zip檔案的壓縮與解壓,此過程所需jar包點選連結下載 下載連結