Java实现解压缩文件和文件夹

2.2 压缩文件或文件树


此方法将文件夹下的所有文件按原有的树形结构压缩到文件中,也支持压缩单个文件。原理也简单,无非就是递归遍历文件树中的每一个文件,进行压缩。有个注意的点每一个文件的写入路径是基于压缩文件位置的相对路径。

package com.nobody.zip;

import java.io.*;

import java.util.zip.ZipEntry;

import java.util.zip.ZipInputStream;

import java.util.zip.ZipOutputStream;

public class ZipUtils {

/**

  • 压缩文件或文件夹(包括所有子目录文件)

  • @param sourceFile 源文件

  • @param format 格式(zip或rar)

  • @throws IOException 异常信息

*/

public static void zipFileTree(File sourceFile, String format) throws IOException {

ZipOutputStream zipOutputStream = null;

try {

String zipFileName;

if (sourceFile.isDirectory()) { // 目录

zipFileName = sourceFile.getParent() + File.separator + sourceFile.getName() + “.”

  • format;

} else { // 单个文件

zipFileName = sourceFile.getParent()

  • sourceFile.getName().substring(0, sourceFile.getName().lastIndexOf(“.”))

  • “.” + format;

}

// 压缩输出流

zipOutputStream = new ZipOutputStream(new FileOutputStream(zipFileName));

zip(sourceFile, zipOutputStream, “”);

} finally {

if (null != zipOutputStream) {

// 关闭流

try {

zipOutputStream.close();

} catch (IOException ex) {

ex.printStackTrace();

}

}

}

}

/**

  • 递归压缩文件

  • @param file 当前文件

  • @param zipOutputStream 压缩输出流

  • @param relativePath 相对路径

  • @throws IOException IO异常

*/

private static void zip(File file, ZipOutputStream zipOutputStream, String relativePath)

throws IOException {

FileInputStream fileInputStream = null;

try {

if (file.isDirectory()) { // 当前为文件夹

// 当前文件夹下的所有文件

File[] list = file.listFiles();

if (null != list) {

// 计算当前的

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值