/**
*
* 方法简介.fileOrDirectory :源文件路径,compfile : zipfile
*
* @author HSG
* @date 创建时间 2018年7月4日
* @since V1.0
*/
public static void compressFileToZip(File fileOrDirectory,
File compfile) throws IOException {
ZipOutputStream out = null;
try {
out = new ZipOutputStream(compfile);
out.setEncoding("GBK");
if (fileOrDirectory.isFile()) {
zipFileOrDirectory(out, fileOrDirectory, "");
} else {
File[] entries = fileOrDirectory.listFiles();
for (int i = 0; i < entries.length; i++) {
zipFileOrDirectory(out, entries[i], "");
}
}
compfile = null;
fileOrDirectory = null;
} catch (IOException ex) {
if (out != null) {
try {
out.close();
} catch (IOException exx) {
throw exx;
}
}
out = null;
ex.printStackTrace();
throw ex;
}
if (out != null) {
try {
out.close();
} catch (IOException ex) {
throw ex;
}
}
out = null;
}
/**
*
* 方法简介.
*
* @author HSG
* @date 创建时间 2018年7月4日
* @since V1.0
*/
private static void zipFileOrDirectory(ZipOutputStream out, File compresobject,
String curPath) throws IOException {
FileInputStream in = null;
try {
if (!compresobject.isDirectory()) {
// 压缩文件
byte[] buffer = new byte[4096];
int bytes_read;
in = new FileInputStream(compresobject);
ZipEntry entry = new ZipEntry(curPath
+ compresobject.getName());
//System.out.println(compresobject.getName());
out.setEncoding("GBK");
out.putNextEntry(entry);
while ((bytes_read = in.read(buffer)) != -1) {
out.write(buffer, 0, bytes_read);
}
out.closeEntry();
} else {
// 压缩目录
File[] entries = compresobject.listFiles();
for (int i = 0; i < entries.length; i++) {
// 递归压缩,更新curPaths
zipFileOrDirectory(out, entries[i], curPath
+ compresobject.getName() + "/");
}
}
} catch (IOException ex) {
ex.printStackTrace();
throw ex;
} finally {
if (in != null) {
try {
in.close();
} catch (IOException ex) {
ex.printStackTrace();
throw ex;
}
}
in = null;
}
}
相关文章
- 11-12Cause: java.sql.SQLException: ORA-12899: 列 “SGWPDM“.“PM_BID_PROJECT_INFO_COPY1“.“BID_TYPE_CODE“ 的值太大
- 11-12java-清理内存后,Android应用程序崩溃
- 11-12[从0到1搭建ABP微服务] - 文章目录
- 11-12浅入 ABP 系列教程目录汇总
- 11-12在Eclipse中创建Dynamic Web Project具有和MyEclipse中Web Project一样的目录结构
- 11-12AIX下find命令不递归删除目录
- 11-12java – 时间执行Groovy与Beanshell的巨大差异
- 11-12VS20xx下项目开发目录管理方法
- 11-12python3 简单web目录扫描脚本(后续更新完整)
- 11-12Qt plugins(插件)目录