一切皆可抽象

大而无形 庖丁解牛 厚积薄发 涤虑玄览
   ::  ::  ::  ::  :: 管理

【原创】java写的压缩、解压的代码

Posted on 2005-10-28 15:04 锋出磨砺 阅读(888) 评论(2)  编辑  收藏 所属分类: java算法

import java.io.*;
import java.util.*;
import java.util.zip.ZipOutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;

public class FileMgr {
  public FileMgr() {
  }
 /**
   * 压缩文件
   * @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));
      // 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();
    }
    catch (IOException e) {
      e.printStackTrace();
    }
  }

  /**
   * 解压缩
   * @param zipfile File 需要解压缩的文件
   * @param descDir String  解压后的目标目录
   */
  public static void UnZipFiles(java.io.File zipfile, String descDir) {
    try {
      // Open the ZIP file
      ZipFile zf = new ZipFile(zipfile);
      for (Enumeration entries = zf.entries(); entries.hasMoreElements(); ) {
        // Get the entry name
        ZipEntry entry = ( (ZipEntry) entries.nextElement());
        String zipEntryName = entry.getName();
        InputStream in = zf.getInputStream(entry);
       // System.out.println(zipEntryName);
        OutputStream out = new FileOutputStream(descDir + zipEntryName);
        byte[] buf1 = new byte[1024];
        int len;
        while ( (len = in.read(buf1)) > 0) {
          out.write(buf1, 0, len);
        }
        // Close the file and stream
        in.close();
        out.close();
      }
    }
    catch (IOException e) {
      e.printStackTrace();
    }
  }

}


评论

# re: 【原创】java写的压缩、解压的代码  回复  更多评论   

2006-05-16 15:03 by whw
guanyong ma

# re: 【原创】java写的压缩、解压的代码  回复  更多评论   

2006-05-16 15:04 by whw
能用吗?

只有注册用户登录后才能发表评论。


网站导航: