解压缩文件java源码

//文件名中有中文会有错误

package unzip;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;

public class newUnZip {

 public static void main(String[] args) throws Exception {
  newUnZip unzip = new newUnZip();
  String zippath = "D://temp//";
  String zipDir = "D://data//";

  File file = new File(zipDir);
  List<File> list = unzip.getSubFiles(file);
  for (Object obj : list) {//获得文件列表
   String realname = ((File) obj).getName();
   unzip.ReadZip(zippath, zipDir + realname);
  }
 }

 public void ReadZip(String zippath, String unzipPath) throws Exception {
  ZipFile zfile = new ZipFile(unzipPath);// creat zip object
  Enumeration zList = zfile.entries();
  ZipEntry ze = null;
  byte[] buf = new byte[2048];

  BufferedOutputStream os = null;
  BufferedInputStream is = null;

  /**
   * get every file in zip file
   */
  while (zList.hasMoreElements()) {
   // get ZipEntry from ZipFile
   ze = (ZipEntry) zList.nextElement();
   
   //create directory
   if (ze.isDirectory()) {
//    File directory = new File(olddirec.getParent(), entry
//      .getName());
    File directory = new File("d://temp", ze
      .getName());

    if (!directory.exists())
     if (!directory.mkdirs())
      System.exit(0);
    continue;
   }
   /****************************************/
   
   is = new BufferedInputStream(zfile.getInputStream(ze));
   os = new BufferedOutputStream(new FileOutputStream(getRealFileName(
     zippath, ze.getName())));

   int readLen = 0;
   while ((readLen = is.read(buf, 0, 2048)) != -1) {
    os.write(buf, 0, readLen);
   }

   os.flush();
   os.close();
   is.close();
  }
  zfile.close();
 }

 private File getRealFileName(String zippath, String absFileName) {
  String[] dirs = absFileName.split("/", absFileName.length());
  File ret = new File(zippath);
  if (dirs.length > 0) {
   for (int i = 0; i < dirs.length; i++) {
    ret = new File(ret, dirs[i]);
   }
  }
  return ret;
 }

 private List<File> getSubFiles(File baseDir) {
  List<File> ret = new ArrayList<File>();
  File[] tmp = baseDir.listFiles();
  for (int i = 0; i < tmp.length; i++) {
   if (tmp[i].isFile()) {
    ret.add(tmp[i]);
   }

   if (tmp[i].isDirectory()) {
    ret.addAll(getSubFiles(tmp[i]));
   }
  }
  return ret;
 }
}
 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值