开发学院WEB开发Jsp 用Java压缩文件或目录下的所有文件 阅读

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

 2008-01-05 08:31:39 来源:WEB开发网   
核心提示:import java.io.File;import org.apache.tools.zip.ZipOutputStream;import java.io.FileInputStream;import java.io.FileOutputStream;/*** @author tyrone**/public clas


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();
 }
}
}


Tags:Java 压缩 文件

编辑录入:爽爽 [复制链接] [打 印]
[]
  • 好
  • 好的评价 如果觉得好,就请您
      0%(0)
  • 差
  • 差的评价 如果觉得差,就请您
      0%(0)
赞助商链接