本文主要是介绍Java生成zip包并下载,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
通过流在内存中直接生成zip,或者字符串生成zip
1.根据已有的文件或者字符串,生成Zip输出流,从浏览器下载zip包
jar包ant-1.6.5.jar
指定文件打包,或者指定字符串压缩成指定文件,并下载
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.io.IOUtils;
import org.apache.tools.zip.ZipEntry;
import org.apache.tools.zip.ZipOutputStream;
/**
* 类说明:压缩指定文件,到指定目录/文件
*/
public class ZipUtil extends HttpServlet {
private static final long serialVersionUID = 1L;
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String zipFileName = "下载文件名称.zip";
response.reset();
response.setHeader("Pragma", "public");
response.setCharacterEncoding("UTF-8");
response.setContentType("application/zip; charset=utf-8");
response.addHeader("Content-Disposition","attachment;fileName="+new String(zipFileName.getBytes("GBK"),"ISO-8859-1"));
File file = new File("E:/test.dat");
try {
downloadZip(file, response);
} catch (Exception e) {
e.printStackTrace();
}
}
public void downloadZip(File srcFile, HttpServletResponse response) throws Exception{
OutputStream out = null;
In
这篇关于Java生成zip包并下载的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!