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


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值