Java解压文件

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Enumeration;
import org.apache.tools.zip.ZipEntry;
import org.apache.tools.zip.ZipFile;


public class Zip2File {
/**
 * 创建目录
 * @param path
 * 目录绝对路径名
 */
static void createDir(String path) {
 File dir = new File(path);
 if (dir.exists() == false)
  dir.mkdir();
}
/**
 * 解压zip文件
 * @param zipFilePath
 *            zip文件绝对路径
 * @param unzipDirectory
 *            解压到的确
 * @throws Exception
 */
@SuppressWarnings("rawtypes")
public static void unzip(String zipFilePath, String unzipDirectory)throws Exception {
 File file = new File(zipFilePath);
 ZipFile zipFile = new ZipFile(file);
 // 创建本zip文件解压目录
 File unzipFile = new File(unzipDirectory);
 if (unzipFile.exists())
 unzipFile.delete();
 unzipFile.mkdir();
 // 得到zip文件条目枚举对象
 Enumeration zipEnum = zipFile.getEntries();
 // 定义输入输出流对象
 InputStream input = null;
 OutputStream output = null;
 // 定义对象
 ZipEntry entry = null;
 // 循环读取条目
 while (zipEnum.hasMoreElements()) {
 // 得到当前条目
 entry = (ZipEntry) zipEnum.nextElement();
 String entryName = new String(entry.getName());
 // 用/分隔条目名称
 String names[] = entryName.split("\\/");
 int length = names.length;
 String path = unzipFile.getAbsolutePath();
 System.out.println(path+"----");
 for (int v = 0; v < length; v++) {
   if (v < length - 1) { // 最后一个目录之前的目录
    path += "/" + names[v] + "/";
    createDir(path);
   } else { // 最后一个
    if (entryName.endsWith("/")) // 为目录,则创建文件夹
         createDir(unzipFile.getAbsolutePath() + "/"+entryName);
    else { // 为文件,则输出到文件
     input = zipFile.getInputStream(entry);
     output = new FileOutputStream(new File(unzipFile.getAbsolutePath()+ "/" + entryName));
     byte[] buffer = new byte[1024 * 8];
     int readLen = 0;
     while ((readLen = input.read(buffer, 0, 1024 * 8)) != -1)
     output.write(buffer, 0, readLen);
     input.close();
     output.flush();
     output.close();
    }
   }
  }
  }
}
 
public static void main(String[] args) throws Exception {
unzip("D:\\1.zip", "D:\\新");
    System.out.println("over....................");
}
 
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值