Java压缩(文件或目录)

这几天学习Java IO,老师让做一个Java Zip压缩程序,参考了网上的一些很不错的代码,结合自己的需要,写了下面这段代码:

/**
 *
 */
package zxcTest;

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

/**
 * @author Xiaocaho Zhao
 *
 */
public class Compressfile {

 /**
  * @param args
  * @throws IOException
  */
 public static void main(String[] args) throws IOException {
  // TODO Auto-generated method stub
  //需要压缩的文件或目录的路径
  File file = new File("C:/Users/Administrator/Desktop/java_zip");
  if(file.canRead())
  {
   //FileOutputStream的文件路径必须带后缀,不然会出现“文件无法访问的异常”
   ZipOutputStream out = new ZipOutputStream(
    new FileOutputStream(file.getPath() + ".zip"));
   //找到最后一个‘/’的位置,以便取出当前的文件名或目录名
   Zip(file.getPath(),file.getPath().lastIndexOf("//"),out);
   out.closeEntry();
   out.close();

  }else{
   System.out.println("file can not read.");
  }
 }
 
 public static void Zip(String path,int baseindex,ZipOutputStream out) throws IOException{
  //要压缩的目录或文件
  File file = new File(path);
  File[] files;
  if(file.isDirectory()){//若是目录,则列出所有的子目录和文件
   files = file.listFiles();
  }else{//若为文件,则files数组只含有一个文件
   files = new File[1];
   files[0] = file;
  }
  
  for(File f:files){
   if(f.isDirectory()){
    //去掉压缩根目录以上的路径串,一面ZIP文件中含有压缩根目录父目录的层次结构
    String pathname = f.getPath().substring(baseindex+1);
    //空目录也要新建哟个项
    out.putNextEntry(new ZipEntry(pathname + "/"));
    //递归
    Zip(f.getPath(),baseindex,out);
   }else{
    //去掉压缩根目录以上的路径串,一面ZIP文件中含有压缩根目录父目录的层次结构
    String pathname = f.getPath().substring(baseindex+1);
    //新建项为一个文件
    out.putNextEntry(new ZipEntry(pathname));
    //读文件
    BufferedInputStream in = new BufferedInputStream(
      new FileInputStream(f));
    int c;
    while((c=in.read()) != -1)
     out.write(c);
    in.close();
   }
  }
 }
}


发布了30 篇原创文章 · 获赞 31 · 访问量 35万+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章