Java文件压缩

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ page import="java.net.URLEncoder" %>
<%@ page import="java.io.*" %>
<%@ page import="java.util.*" %>
<%@ page import="org.apache.tools.zip.ZipEntry" %>
<%@ page import="org.apache.tools.zip.ZipOutputStream" %>


<%!
	public void zip(String inputFileName, String zipFileName) throws Exception {
		zip(zipFileName, new File(inputFileName));
	}

	private void zip(String zipFileName, File inputFile) throws Exception {
		ZipOutputStream out = new ZipOutputStream(new FileOutputStream(
				zipFileName));
		zip(out, inputFile, "");
		out.close();
	}

	private void zip(ZipOutputStream out, File f, String base) throws Exception {
		if (f.isDirectory()) {
			File[] fl = f.listFiles();
			out.putNextEntry(new org.apache.tools.zip.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 org.apache.tools.zip.ZipEntry(base));
			FileInputStream in = new FileInputStream(f);
			int b;
			while ((b = in.read()) != -1) {
				out.write(b);
			}
			in.close();
		}
	}
	
	
	//创建文件夹
	public String createFolder()
	{
		int y,m,d; 
		Calendar cal=Calendar.getInstance(); 
		y=cal.get(Calendar.YEAR); 
		m=cal.get(Calendar.MONTH); 
		d=cal.get(Calendar.DATE);
		//List<String> folders = new ArrayList<String>();
		String nowDate = y + "-" + m + "-" + d;
		File file = new File("E:\\apache-tomcat-5.5.26\\hz\\huazhong_system_root\\bgraserver.gicp.net\\webapps\\ROOT\\cccccc\\" + nowDate);
		file.mkdir();
		return file.getPath();
	}
%>

<%
	String path = createFolder();//创建文件夹,并得到文件夹路径
	File file = new File(path);
	String zipName = file.getParent() + "\\" + file.getName() + ".zip";
	zip(path, zipName);

	out.println(zipName);

	out.println("压缩成功,<a href='" + file.getName() + ".zip'>点击这里下载</a>");	
%>

posted @ 2010-04-07 08:46  Me疯子_(~  阅读(116)  评论(0编辑  收藏  举报