首页 | 社区 | 博客 | 招聘 | 文章 | 新闻 | 下载 | 项目交易 | 网友作品 | 读书 | ACM题库 | 源码
亲,您未登录哦! 登录 | 注册

用Java压缩文件或目录下的所有文件

(加入日期: 2005-07-31 )

打印文章】【字体:

分享到:
import java.io.File;
import org.apache.tools.zip.ZipOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
/**
* @author tyrone
*
*/
public class DirectoryZip {
/**
  *@param inputFileName, file or directory waiting for zipping ,outputFileName output file name
  *
  */
public void zip(String inputFileName,String outputFileName) throws Exception {
  ZipOutputStream out = new ZipOutputStream(new FileOutputStream(outputFileName));
  zip(out, new File(inputFileName), "");
  System.out.println("zip done");
  out.close();
}
private void zip(ZipOutputStream out, File f, String base) throws Exception {
  if (f.isDirectory()) {
   File[] fl = f.listFiles();
   if (System.getProperty("os.name").startsWith("Windows")){
    out.putNextEntry(new org.apache.tools.zip.ZipEntry(base + "\\"));
    base = base.length() == 0 ? "" : base + "\\";
   }
   else{
    out.putNextEntry(new org.apache.tools.zip.ZipEntry(base + "/"));
    base = base.length() == 0 ? "" : base + "/";
   }
   for (int i = 0; i < fl.length; i++) {
    zip(out, fl[i], base + fl[i].getName());
   }
  }
  else {
   out.putNextEntry(new org.apache.tools.zip.ZipEntry(base));
   FileInputStream in = new FileInputStream(f);
   int b;
   System.out.println(base);
   while ( (b = in.read()) != -1) {
    out.write(b);
   }
   in.close();
  }
}
public static void main(String[] args){
  DirectoryZip m_zip=new DirectoryZip();
  try{
   m_zip.zip(args[0],"release\\2005.zip");
  }catch(Exception ex){
   ex.printStackTrace();
  }
}
}

本栏文章均来自于互联网,版权归原作者和各发布网站所有,本站收集这些文章仅供学习参考之用。任何人都不能将这些文章用于商业或者其他目的。( Pfan.cn )

编程爱好者论坛

本栏最新文章