一、压缩文件目录"F:\mmd"
二、代码实现
方式 一:采用的是jdk自带的包java.util.zip.ZipOutputStream,不足之处,文件(夹)名称带中文时,出现乱码问题。
<span style="font-family:Microsoft YaHei;font-size:12px;">package com.test; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.Enumeration; import java.util.zip.ZipEntry; import java.util.zip.ZipFile; import java.util.zip.ZipOutputStream; public class TestZip { public static void main(String[] args) throws Exception { //压缩文件 String filePath = "F:/mmd/"; String zipFile = "F:/mmd.zip"; zipFiles(new File(filePath), zipFile); //解压文件 unZipFiles(new File("F:/mmd.zip"), "F:/zipfile/"); } /** * 压缩文件-由于out要在递归调用外,所以封装一个方法用来 调用ZipFiles(ZipOutputStream out,String * path,File... srcFiles) * * @param zip * @param path * @param srcFiles * @throws IOException * @author isea533 */ public static void zipFiles(File srcFile, String zipfile) throws Exception { File ff = new File(zipfile); // 根据文件路径构造一个文件实例 if (!ff.exists()) { ff.createNewFile(); } FileOutputStream out = new FileOutputStream(zipfile); // 根据文件路径构造一个文件输出流 ZipOutputStream zipOut = new ZipOutputStream(out); // 传入文件输出流对象,创建ZIP数据输出流对象 TestZip.zipFiles(zipOut, srcFile.listFiles(), zipfile, ""); zipOut.close(); out.close(); } /** * 压缩文件及文件夹 * * @param zipOut * @param files待压缩的文件路径 * @param zipfile 压缩后的文件名称 * @param path * @throws Exception */ public static void zipFiles(ZipOutputStream zipOut, File[] files,String zipfile, String path) throws Exception { if (path != "") { path = path.replaceAll("\\*", "/"); if (!path.endsWith("/")) { path += "/"; } } for (File file : files) { if (file.isDirectory()) { File[] files2 = file.listFiles(); zipFiles(zipOut, files2, zipfile, path + file.getName()); } else { File f = new File(file.getAbsolutePath()); FileInputStream in = new FileInputStream(f);// 创建文件输入流对象 String fileName = f.getName();// 得到当前文件的文件名称 ZipEntry entry = new ZipEntry(path + fileName);// 创建指向压缩原始文件的入口 zipOut.putNextEntry(entry); int nNumber = 0; byte[] buffer = new byte[1024]; while ((nNumber = in.read(buffer)) != -1) { zipOut.write(buffer, 0, nNumber);// 向压缩文件中输出数据 } in.close(); } } } /** * 解压到指定目录 * @param zipPath * @param descDir */ public static void unZipFiles(String zipPath, String descDir) throws IOException { unZipFiles(new File(zipPath), descDir); } /** * 解压文件到指定目录 * * @param zipFile待解压的文件 * @param descDir指定的解压目录 */ public static void unZipFiles(File zipFile, String descDir) throws IOException { File pathFile = new File(descDir); if (!pathFile.exists()) { pathFile.mkdirs(); } ZipFile zip = new ZipFile(zipFile); for (Enumeration entries = zip.entries(); entries.hasMoreElements();) { ZipEntry entry = (ZipEntry) entries.nextElement(); String zipEntryName = entry.getName(); InputStream in = zip.getInputStream(entry); String outPath = (descDir + zipEntryName).replaceAll("\\*", "/"); File file = new File(outPath.substring(0, outPath.lastIndexOf('/')));// 判断路径是否存在,不存在则创建文件路径 if (!file.exists()) { file.mkdirs(); } if (new File(outPath).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(); } } } </span>
方法二、使用org.apache.tools.zip.ZipOutputStream(测试的中文名称压缩后也出现乱码)
package com.test; import java.io.BufferedInputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.util.Enumeration; import java.util.zip.CRC32; import java.util.zip.CheckedOutputStream; import java.util.zip.ZipOutputStream; import org.apache.tools.zip.ZipEntry; import org.apache.tools.zip.ZipFile; public class ZipCompress { static final int BUFFER = 1024; private File zipFile; public static void main(String[] args) throws Exception { ZipCompress testAntZip = new ZipCompress("F:\\mmdANT.zip"); testAntZip.compress("F:\\mmd\\"); testAntZip.decompressFile("F:/mmdANT.zip", "F:/adsff/"); } public ZipCompress(String pathName) { zipFile = new File(pathName); } /** * 压缩 * @param srcPathName 压缩文件目录 */ public void compress(String srcPathName) { File file = new File(srcPathName); if (!file.exists()) throw new RuntimeException(srcPathName + "不存在!"); try { FileOutputStream fileOutputStream = new FileOutputStream(zipFile); CheckedOutputStream cos = new CheckedOutputStream(fileOutputStream, new CRC32()); ZipOutputStream out = new ZipOutputStream(cos); // out.setEncoding("utf-8"); // //如果不加此句,压缩文件依然可以生成,只是在打开和解压的时候,会显示乱码,但是还是会解压出来 compress(file, out, ""); out.close(); } catch (Exception e) { throw new RuntimeException(e); } } private void compress(File file, ZipOutputStream out, String basedir) { /* 判断是目录还是文件 */ if (file.isDirectory()) { this.compressDirectory(file, out, basedir); } else { this.compressFile(file, out, basedir); } } /** 压缩一个目录 */ private void compressDirectory(File dir, ZipOutputStream out, String basedir) { if (!dir.exists()) { return; } File[] files = dir.listFiles(); for (int i = 0; i < files.length; i++) {/* 递归 */ compress(files[i], out, basedir + dir.getName() + "/"); } } /** 压缩一个文件 */ private void compressFile(File file, ZipOutputStream out, String basedir) { if (!file.exists()) { return; } try { BufferedInputStream bis = new BufferedInputStream( new FileInputStream(file)); ZipEntry entry = new ZipEntry(basedir + file.getName()); out.putNextEntry(entry); int count; byte data[] = new byte[BUFFER]; while ((count = bis.read(data, 0, BUFFER)) != -1) { out.write(data, 0, count); } bis.close(); } catch (Exception e) { throw new RuntimeException(e); } } /** * 解压 */ public void decompressFile(String zipFilePath, String releasePath) throws IOException { ZipFile zipFile = new ZipFile(zipFilePath); Enumeration<ZipEntry> enumeration = zipFile.getEntries(); InputStream inputStream = null; FileOutputStream fileOutputStream = null; ZipEntry zipEntry = null; String zipEntryNameStr = ""; String[] zipEntryNameArray = null; while (enumeration.hasMoreElements()) { zipEntry = enumeration.nextElement(); zipEntryNameStr = zipEntry.getName(); zipEntryNameArray = zipEntryNameStr.split("/"); String path = releasePath; File root = new File(releasePath); if (!root.exists()) { root.mkdir(); } for (int i = 0; i < zipEntryNameArray.length; i++) { if (i < zipEntryNameArray.length - 1) { path = path + File.separator + zipEntryNameArray[i]; new File(path).mkdir(); } else { if (zipEntryNameStr.endsWith(File.separator)) { new File(releasePath + zipEntryNameStr).mkdir(); } else { inputStream = zipFile.getInputStream(zipEntry); fileOutputStream = new FileOutputStream(new File( releasePath + zipEntryNameStr)); byte[] buf = new byte[1024]; int len; while ((len = inputStream.read(buf)) > 0) { fileOutputStream.write(buf, 0, len); } inputStream.close(); fileOutputStream.close(); } } } } zipFile.close(); } }
方法三:可以用ant中的org.apache.tools.ant.taskdefs.Zip来实现,更加简单。 (中文名称不会出现乱码)
package com.test; import java.io.File; import org.apache.tools.ant.Project; import org.apache.tools.ant.taskdefs.Expand; import org.apache.tools.ant.taskdefs.Zip; import org.apache.tools.ant.types.FileSet; public class ZipCompressByAnt { private File zipFile; public static void main(String[] args) { ZipCompressByAnt zipCompressByAnt = new ZipCompressByAnt( "F:\\mmdANT2.zip"); zipCompressByAnt.compress("F:\\mmd\\"); zipCompressByAnt.unZip("F:\\mmdANT2.zip", "F:\\testAnt"); } public ZipCompressByAnt(String pathName) { zipFile = new File(pathName); } /** * 压缩 */ public void compress(String srcPathName) { File srcdir = new File(srcPathName); if (!srcdir.exists()) throw new RuntimeException(srcPathName + "不存在!"); Project prj = new Project(); Zip zip = new Zip(); zip.setProject(prj); zip.setDestFile(zipFile); FileSet fileSet = new FileSet(); fileSet.setProject(prj); fileSet.setDir(srcdir); // fileSet.setIncludes("**/*.java"); 包括哪些文件或文件夹 // eg:zip.setIncludes("*.java"); // fileSet.setExcludes(...); 排除哪些文件或文件夹 zip.addFileset(fileSet); zip.execute(); } /** * 解压 * @param sourceZip 待解压文件路径 * @param destDir 解压到的路径 */ public 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)); e.setSrc(new File(sourceZip)); e.setOverwrite(false); e.setDest(new File(destDir)); /* ant下的zip工具默认压缩编码为UTF-8编码, 而winRAR软件压缩是用的windows默认的GBK或者GB2312编码 所以解压缩时要制定编码格式 */ e.setEncoding("utf-8"); e.execute(); } }