废话不多说,直接上代码:
/** 压缩一个文件或文件夹
* @param sourceFile 你要压缩的文件夹(整个完整路径)
* @param zipFilePath 压缩后的文件(整个完整路径)
* @throws Exception
*/
public static Boolean zip(String sourceFile, String zipFilePath) {
//若目标文件已经存在,先删除
File target = new File(zipFilePath);
if (target.exists())
target.delete();
ZipOutputStream out = null;
try {
out = new ZipOutputStream(new FileOutputStream(zipFilePath));
File srcfile = new File(sourceFile);
zip(srcfile,out, "");
}
catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (out != null)
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return true;
}
/** 压缩多个文件或文件夹
* @param sourceFileList 要压缩的文件路径数组(整个完整路径)
* @param zipFilePath 压缩后的文件(整个完整路径)
* @throws Exception
*/
public static Boolean compress(LinkedList<String> sourceFileList,String zipFilePath){
//若目标文件已经存在,先删除
File target = new File(zipFilePath);
if (target.exists())
target.delete();
ZipOutputStream out = null;
try {
out = new ZipOutputStream(new FileOutputStream(zipFilePath));
for (String sourceFile : sourceFileList) {
File srcfile = new File(sourceFile);
zip(srcfile,out, "");
}
}
catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (out != null)
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return true;
}
//真正干活的两个方法 上面这个是包工头,下面那个是员工 -------相当于中介
private static void zip(File srcfile,ZipOutputStream out,String base) throws Exception {
if (srcfile.isDirectory()) {
File[] fl = srcfile.listFiles();
base = base.length() == 0 ? srcfile.getName()+ "/" : base + "/";
out.putNextEntry(new ZipEntry(base));
for (int i = 0; i < fl.length; i++) {
zip(fl[i], out, base + fl[i].getName());
}
} else {
//压缩单个文件
zipFile(srcfile,out,base);
}
}
//压缩单个文件
private static void zipFile(File srcfile, ZipOutputStream out, String basedir) {
if (!srcfile.exists())
return;
//第一步就直接压缩文件的情况 此时 basedir = 0,要加上文件名
basedir = basedir.length() == 0 ? srcfile.getName() : basedir;
byte[] buf = new byte[1024];
FileInputStream in = null;
try {
int len;
in = new FileInputStream(srcfile);
out.putNextEntry(new ZipEntry(basedir));
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
out.flush();
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (out != null)
out.closeEntry(); //在这里关闭每一个小文件 的 Entry,在最上面两个调用方法中 才 最终关闭 out
if (in != null)
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}