java 文件解压

本文介绍了一种使用Java实现的解压缩方法,该方法能够将指定路径的ZIP文件解压到另一个指定路径,并返回解压后的文件集合。文中详细展示了如何创建目标目录、读取ZIP条目并逐一解压每个文件。
/**
 * 解压文件到指定路径
 *
 * @param filePath
 * @param upZipPath
 * @return 返回解压的文件集合
 */
public static List<File> unZip(String filePath, String upZipPath) {
    List<File> list = new ArrayList<File>();
    int count = -1;
    File file = null;
    InputStream is = null;
    FileOutputStream fos = null;
    BufferedOutputStream bos = null;

    // 生成指定的保存目录
    String savePath = upZipPath;
    if (!new File(savePath).exists()) {
        new File(savePath).mkdirs();
    }

    try {
        ZipFile zipFile = new ZipFile(filePath, "GBK");
        Enumeration enu = zipFile.getEntries();
        while (enu.hasMoreElements()) {
            ZipEntry zipEntry = (ZipEntry) enu.nextElement();
            if (zipEntry.isDirectory()) {
                new File(savePath + "/" + zipEntry.getName()).mkdirs();
                continue;
            }
            if (zipEntry.getName().indexOf("/") != -1) {
                new File(savePath
                        + "/"
                        + zipEntry.getName().substring(0,
                        zipEntry.getName().lastIndexOf("/")))
                        .mkdirs();
            }
            is = zipFile.getInputStream(zipEntry);
            file = new File(savePath + "/" + zipEntry.getName());
            fos = new FileOutputStream(file);
            bos = new BufferedOutputStream(fos, BUFFER);

            byte buf[] = new byte[BUFFER];
            while ((count = is.read(buf)) > -1) {
                bos.write(buf, 0, count);
            }

            bos.flush();
            fos.close();
            is.close();
            list.add(file);
        }

        zipFile.close();
        return list;
    } catch (IOException ioe) {
        log.error(ioe.getMessage());
        return list;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值