Java打包文件目录问 zip文件。
/**
* 资源打包下载类
* Created by Ruan Banshu on 2015/4/13.
*/
public class ZipOpUtil {
private static Logger logger = LoggerFactory.getLogger(ZipOpUtil.class);
/**
* 将多个文件打包到一个zip中
*
* @param sourceFolder
* @param zipFile
* @return
*/
public static boolean zipFile(String sourceFolder, File zipFile){
boolean isOk = true;
File f = new File(sourceFolder);
ZipOutputStream out = null;
try{
if(!f.exists()){
f.mkdirs();
}
out = new ZipOutputStream(new FileOutputStream(zipFile));
zip(out, f, "");
out.flush();
FileUtils.deleteDirectory(f);
} catch (Exception e){
e.printStackTrace();
throw new AppException("压缩文件出错!");
} finally
{
if(null != out){
try{ out.close(); } catch (Exception e){ e.printStackTrace();}
}
}
return isOk;
}
/**
* 递归压缩文件
* @param out
* @param f
* @param base
* @throws Exception
*/
private static void zip(ZipOutputStream out, File f, String base) throws Exception {
if (f.isDirectory()) {
File[] fl = f.listFiles();
out.putNextEntry(new ZipEntry(base + "/"));
base = base.length() == 0 ? "" : base + "/";
for (int i = 0; i < fl.length; i++) {
zip(out, fl[i], base + fl[i].getName());
}
}else {
out.putNextEntry(new ZipEntry(base));
FileInputStream in = new FileInputStream(f);
int b;
logger.info(base);
while ( (b = in.read()) != -1) {
out.write(b);
}
in.close();
}
}
/**
* 下载单个文件
*
* @param file
* @param request
* @param response
* @return
*/
public static boolean downFile(File file, HttpServletRequest request, HttpServletResponse response) {
boolean isOk = true;
OutputStream myout = null;
FileInputStream fis = null;
BufferedInputStream buff = null;
HttpSession session = request.getSession();
if (session != null) {
session.setAttribute("state", "");
}
try {
response.setContentType("application/x-msdownload");
response.setContentLength((int) file.length());
response.setHeader("content-disposition", "attachment;filename=" + new String(file.getName().getBytes("utf-8"), "ISO8859-1"));
fis = new FileInputStream(file);
buff = new BufferedInputStream(fis);
byte[] b = new byte[1024 * 10];//相当于我们的缓存
long k = 0;//该值用于计算当前实际下载了多少字节
//从response对象中得到输出流,准备下载
myout = response.getOutputStream();
while (k < file.length()) {
int j = buff.read(b, 0, b.length);
k += j;
//将b中的数据写到客户端的内存
myout.write(b, 0, j);
}
myout.flush();
} catch (Exception e) {
e.printStackTrace();
isOk = false;
} finally {
try {
if (null != myout) {
myout.close();
myout = null;
}
if (null != buff) {
buff.close();
buff = null;
}
if (null != fis) {
fis.close();
fis = null;
}
if(file.exists()){
ZipOpUtil.delFile(file);
}
} catch (Exception e) {
e.printStackTrace();
}
}
return isOk;
}
/**
* 删除单个文件
*
* @param file
* @return
*/
public static boolean delFile(File file) {
boolean isOk = true;
try {
if (file.isFile() && file.exists()) {
file.delete();
}
} catch (Exception e) {
e.printStackTrace();
isOk = false;
} finally {
// log ...
}
return isOk;
}