java压缩文件方法

来源:互联网 发布:html 图片存进数据库 编辑:程序博客网 时间:2024/05/18 17:39
/**   * 压缩文件   * @param srcfile File[] 需要压缩的文件列表   * @param zipfile File    压缩后的文件   */public static void ZipFiles(java.io.File[] srcfile, java.io.File zipfile) {    byte[] buf = new byte[1024];    try {      // Create the ZIP file      ZipOutputStream out = new ZipOutputStream(new FileOutputStream(zipfile));     //ZipOutputStream out = new ZipOutputStream(Response.getOutputStream());--设置成这样可以不用保存在本地,再输出, 通过response流输出。      // Compress the files      for (int i = 0; i < srcfile.length; i++) {        FileInputStream in = new FileInputStream(srcfile[i]);        // Add ZIP entry to output stream.        out.putNextEntry(new ZipEntry(srcfile[i].getName()));        // Transfer bytes from the file to the ZIP file        int len;        while ( (len = in.read(buf)) > 0) {          out.write(buf, 0, len);        }        // Complete the entry        out.closeEntry();        in.close();      }      // Complete the ZIP file      out.close();      System.out.println("压缩完成.");    }catch (IOException e) {      e.printStackTrace();    }}

0 0
原创粉丝点击