前面介绍的使用第三方的jar进行压缩,下面介绍使用jdk自带的方法进行压缩:
Test:
package com.home; import java.io.IOException; public class Test { public Test() { try { ZipUtil.doZip("D://test", "D://test1.zip");// 压缩整个文件来 ZipUtil.doZip("D://test.doc", "D://test2.zip");// 压缩单个文件 } catch (IOException e) { e.printStackTrace(); } } public static void main(String[] args) { new Test(); } }
ZipUtil:
package com.home; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.util.zip.ZipEntry; import java.util.zip.ZipOutputStream; public class ZipUtil { /** * 压缩的接口 * * @param src * 源文件全路径 * @param des * 目标zip文件全路径 * @throws IOException */ public static void doZip(String src, String des) throws IOException { File srcFile = new File(src);// 源文件 File zipFile = new File(des);// 目标zip文件 ZipOutputStream zos = null; try { zos = new ZipOutputStream(new BufferedOutputStream( new FileOutputStream(zipFile))); String basePath = null; if (srcFile.isDirectory()) { basePath = srcFile.getPath(); } else { basePath = srcFile.getParent(); } zipFile(srcFile, basePath, zos); } finally { if (zos != null) { zos.closeEntry(); zos.close(); } } } /** * 压缩文件 * * @param srcFile * @param basePath * @param zos * @throws IOException */ private static void zipFile(File srcFile, String basePath, ZipOutputStream zos) throws IOException { File[] files = null; if (srcFile.isDirectory()) { files = srcFile.listFiles(); } else { files = new File[1]; files[0] = srcFile; } BufferedInputStream bis = null; String pathName; byte[] buf = new byte[1024]; int len = 0; try { for (File file : files) { if (file.isDirectory()) { if (!basePath.endsWith("\\")) { basePath += "\\"; } pathName = file.getPath().substring(basePath.length()) + "\\"; zos.putNextEntry(new ZipEntry(pathName)); zipFile(file, basePath, zos); } else { if (!basePath.endsWith("\\")) { basePath += "\\"; } pathName = file.getPath().substring(basePath.length()); bis = new BufferedInputStream(new FileInputStream(file)); zos.putNextEntry(new ZipEntry(pathName)); while ((len = bis.read(buf)) > 0) { zos.write(buf, 0, len); } } } } finally { if (bis != null) { bis.close(); } } } }
原文:http://blog.csdn.net/u010142437/article/details/23307609