文件与文件夹的压缩,其实本质上都是文件的压缩,只是文件夹在压缩时,要判断是否为文件夹,以及文件夹下是否有文件;而同时要处理空文件夹,即空文件夹是否要压缩进zip包中。
file.isDirectory():返回值为Boolean,true代表当前文件是文件夹;
file.listFiles():返回值为file类型的数组,存储的是file;使用该方法可以判断文件夹下是否还有内容(包括文件、文件夹),即用来判断是否为空文件夹;
当是一个文件时,调用ZipOutputStream输出流;
最后不要忘记关闭BufferedInputStream;
直接上代码:
import java.io.*;
import java.util.List;
import java.util.zip.CRC32;
import java.util.zip.CheckedOutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;/*** @Description 将文件或文件夹生成压缩包* @Version V1.0**/public class GenerateZipUtil {static final int BUFFER = 8192;private File zipFile;public GenerateZipUtil(String pathName) {zipFile = new File(pathName);}/*** 多个文件夹* @param pathName 文件路径的集合*/public void compress(List pathName) {ZipOutputStream out = null;try {FileOutputStream fileOutputStream = new FileOutputStream(zipFile);CheckedOutputStream cos = new CheckedOutputStream(fileOutputStream, new CRC32());out = new ZipOutputStream(cos);String basedir = "";for (int i = 0; i < pathName.size(); i++) {compress(new File((String) pathName.get(i)), out, basedir);}out.close();} catch (Exception e) {throw new RuntimeException(e);}}/*** 单个文件(夹)的压缩* @param srcPathName 文件路径*/public void compress(String srcPathName) {File file = new File(srcPathName);if (!file.exists())throw new RuntimeException("要压缩的文件:" + srcPathName + "不存在!");try {FileOutputStream fileOutputStream = new FileOutputStream(zipFile);CheckedOutputStream cos = new CheckedOutputStream(fileOutputStream, new CRC32());ZipOutputStream out = new ZipOutputStream(cos);String basedir = "";compress(file, out, basedir);out.close();} catch (Exception e) {throw new RuntimeException(e);}}/*** 压缩文件(夹)* @param file 文件/文件夹* @param out 压缩包输出流* @param basedir 根文件路径*/private void compress(File file, ZipOutputStream out, String basedir) {// 判断是目录还是文件if (file.isDirectory()) {this.compressDirectory(file, out, basedir);} else {this.compressFile(file, out, basedir);}}/*** 压缩一个目录,文件夹* @param dir 文件夹* @param out 输出流* @param basedir 根路径*/private void compressDirectory(File dir, ZipOutputStream out, String basedir) {if (!dir.exists())return;try {File[] files = dir.listFiles();if (files.length == 0) {// 空文件夹的处理,空目录也打包进去,加上/表示是一个目录out.putNextEntry(new ZipEntry(basedir + dir.getName() + "/"));out.closeEntry();} else {for (int i = 0; i < files.length; i++) {/* 递归 */compress(files[i], out, basedir + dir.getName() + "/");}}} catch (Exception e) {e.printStackTrace();}}/*** 压缩一个文件* @param file 文件* @param out 输出流* @param basedir 根路径*/private void compressFile(File file, ZipOutputStream out, String basedir) {if (!file.exists()) {return;}try {BufferedInputStream bis = new BufferedInputStream( new FileInputStream(file));ZipEntry entry = new ZipEntry(basedir + file.getName());out.putNextEntry(entry);int count;byte data[] = new byte[BUFFER];while ((count = bis.read(data, 0, BUFFER)) != -1) {out.write(data, 0, count);}bis.close();} catch (Exception e) {throw new RuntimeException(e);}}}