压缩文件
1. 依赖
<!-- ant.jar 用于解决文件解压缩乱码问题 -->
<dependency>
<groupId>ant</groupId>
<artifactId>ant</artifactId>
<version>1.6.5</version>
</dependency>
2. 代码
/**
* 压缩文件
* @param srcFileList 需要被压缩的文件集合
* @param zipFile 压缩的文件对象
* File zipFile = new File(路径 + ".zip");
*/
private void zipFiles(List<File> srcFileList, File zipFile) {
byte[] buf = new byte[1024];
ZipOutputStream out = null;
FileInputStream in = null;
try
{
out = new ZipOutputStream(new FileOutputStream(zipFile));
for (int i = 0; i < srcFileList.size(); i++)
{
in = new FileInputStream(srcFileList.get(i));
out.putNextEntry(new ZipEntry(srcFileList.get(i).getName()));
int len;
while ((len = in.read(buf)) > 0)
{
out.write(buf, 0, len);
}
out.setEncoding("GBK");
out.closeEntry();
}
} catch (Exception e)
{
e.printStackTrace();
log.error(e);
}finally
{
try
{
if (out != null)
{
out.close();
}
} catch (IOException e)
{
e.printStackTrace();
log.error(e);
}
try
{
if (in != null)
{
in.close();
}
} catch (IOException e)
{
e.printStackTrace();
log.error(e);
}
}
}