想要对文件进行压缩操作,这就需要用到ZipOutputStream来对文件压缩操作。首先需要指明的是:ZipOutputStream如果使用java自带的api操作需要1.7以上,否则会出现中文乱码,我测试过1.6和1.8,1.6会出现乱码,1.8则不会。听说1.7已解决这个问题,但是没实操过。如果项目中使用的是jdk1.6没办法改,这时我们就需要引进apache的ant.jar,使用它提供的ZipEntry和ZipOutputStream接口
public class ZipCompress { private String zipFileName; //目的地Zip文件 private String sourceFileName; //源文件 public ZipCompress(String zipFileName, String sourceFileName) { this.zipFileName = zipFileName; this.sourceFileName = sourceFileName; } public void zip() throws Exception { System.out.println("开始压缩..."); //创建zip输出流 ZipOutputStream out = new ZipOutputStream(new FileOutputStream(zipFileName)); File sourceFile = new File(sourceFileName); //调用函数 compress(out, sourceFile, sourceFile.getName()); out.close(); System.out.println("压缩完成!"); } public void compress(ZipOutputStream out, File sourceFile, String base) throws Exception { //如果路径为目录(文件夹) if(sourceFile.isDirectory()) { //取出文件夹中的文件(或子文件夹) File[] flist = sourceFile.listFiles(); if(flist.length==0) {//如果文件夹为空,则只需在目的地zip文件中写入一个目录进入点 System.out.println(base + File.separator); out.putNextEntry(new ZipEntry(base + File.separator)); } else {//如果文件夹不为空,则递归调用compress,文件夹中的每一个文件(或文件夹)进行压缩 for(int i=0; i<flist.length; i++) { compress(out, flist[i], base+File.separator+flist[i].getName()); } } } else { out.putNextEntry(new ZipEntry(base)); FileInputStream fos = new FileInputStream(sourceFile); BufferedInputStream bis = new BufferedInputStream(fos); int len; byte[] buf = new byte[1024]; System.out.println(base); while((len=bis.read(buf, 0, 1024)) != -1) { out.write(buf, 0, len); } bis.close(); fos.close(); } } }
public class TestZip { public static void main(String[] args) { ZipCompress zipCom = new ZipCompress("E:\\test\\压缩文件包.zip", "E:\\test\\temp"); try { zipCom.zip(); } catch (Exception e) { e.printStackTrace(); } } }