AndroidTolls Git地址:https://github.com/wisesun7/AndroidTools.git
???? 本篇提供了一些压缩文件的方法,可对单个或批量文件(夹)进行压缩。
*** Created by wise on 2019/6/19.* {
@link #zipFile(File, ZipOutputStream, String)}* {
@link #zipFiles(Collection, File)}* {
@link #zipFiles(Collection, File, String)}*/public class ZipUtils {
private static final int BUFF_SIZE = 1024 * 1024; //1M/*** 批量压缩文件(夹)** @param resFileList 要压缩的文件(夹)列表* @param zipFile 生成的压缩文件* @throws IOException 当压缩过程出错时抛出*/public static void zipFiles(Collection<File> resFileList, File zipFile) throws IOException {
ZipOutputStream zipout = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(zipFile), BUFF_SIZE));for (File resFile : resFileList) {
zipFile(resFile, zipout, "");}zipout.close();}/*** 批量压缩文件(夹)** @param resFileList 要压缩的文件(夹)列表* @param zipFile 生成的压缩文件* @param comment 压缩文件的注释* @throws IOException 当压缩过程出错时抛出*/public static void zipFiles(Collection<File> resFileList, File zipFile, String comment) throws IOException {
ZipOutputStream zipout = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(zipFile), BUFF_SIZE));for (File resFile : resFileList) {
zipFile(resFile, zipout, "");}zipout.setComment(comment);zipout.close();}/*** 压缩文件** @param resFile 需要压缩的文件(夹)* @param zipout 压缩的目的文件* @param rootpath 压缩的文件路径* @throws FileNotFoundException 找不到文件时抛出* @throws IOException 当压缩过程出错时抛出*/private static void zipFile(File resFile, ZipOutputStream zipout, String rootpath) throws FileNotFoundException, IOException {
rootpath = rootpath + (rootpath.trim().length() == 0 ? "" : File.separator)+ resFile.getName();rootpath = new String(rootpath.getBytes("8859_1"), "GB2312");if (resFile.isDirectory()) {
File[] fileList = resFile.listFiles();if (fileList != null) {
for (File file : fileList) {
zipFile(file, zipout, rootpath);}}} else {
byte buffer[] = new byte[BUFF_SIZE];BufferedInputStream in = new BufferedInputStream(new FileInputStream(resFile),BUFF_SIZE);zipout.putNextEntry(new ZipEntry(rootpath));int realLength;while ((realLength = in.read(buffer)) != -1) {
zipout.write(buffer, 0, realLength);}in.close();zipout.flush();zipout.closeEntry();}}
}