zoukankan      html  css  js  c++  java
  • [转贴]Compress files using the Java ZIP API

    http://www.java2s.com/Code/Java/File-Input-Output/CompressfilesusingtheJavaZIPAPI.htm

    Compress files using the Java ZIP API



    import java.io.File;
    import java.io.FileInputStream;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.util.zip.GZIPOutputStream;
    import java.util.zip.ZipEntry;
    import java.util.zip.ZipOutputStream;

    public class Compress {
      public static void gzipFile(String from, String to) throws IOException {
      FileInputStream in = new FileInputStream(from);
      GZIPOutputStream out = new GZIPOutputStream(new FileOutputStream(to));
      byte[] buffer = new byte[4096];
      int bytesRead;
      while ((bytesRead = in.read(buffer)) != -1)
      out.write(buffer, 0, bytesRead);
      in.close();
      out.close();
      }

      /** Zip the contents of the directory, and save it in the zipfile */
      public static void zipDirectory(String dir, String zipfile)
      throws IOException, IllegalArgumentException {
      // Check that the directory is a directory, and get its contents
      File d = new File(dir);
      if (!d.isDirectory())
      throw new IllegalArgumentException("Not a directory: "
      + dir);
      String[] entries = d.list();
      byte[] buffer = new byte[4096]; // Create a buffer for copying
      int bytesRead;

      ZipOutputStream out = new ZipOutputStream(new FileOutputStream(zipfile));

      for (int i = 0; i < entries.length; i++) {
      File f = new File(d, entries[i]);
      if (f.isDirectory())
      continue;//Ignore directory
      FileInputStream in = new FileInputStream(f); // Stream to read file
      ZipEntry entry = new ZipEntry(f.getPath()); // Make a ZipEntry
      out.putNextEntry(entry); // Store entry
      while ((bytesRead = in.read(buffer)) != -1)
      out.write(buffer, 0, bytesRead);
      in.close(); 
      }
      out.close();
      }

      public static void main(String args[]) throws IOException {
      String from = ".";
      File f = new File(from);
      boolean directory = f.isDirectory(); // Is it a file or directory?

      Compress.zipDirectory(from, from + ".zip");
      Compress.gzipFile(from, from + ".gz");
      }
    }

  • 相关阅读:
    Centos安装Memcached和(Nginx)Memcache扩展详细教程
    文章已被删除!
    phonegap安卓手机开发入门
    微信分享链接带图片文字和描述
    CSDN数据库被爆 统计CSDN用户都喜欢哪些密码
    ...
    重新初始化 VS2010
    spark系列之基本概念
    python 数字字典加密非汉字
    MySQL 5.7实现 row_number窗口函数
  • 原文地址:https://www.cnblogs.com/Samsara/p/1296894.html
Copyright © 2011-2022 走看看