1、ZIP檔案格式
[local file header + file data + data descriptor]{1,n} + central directory + end of central directory record 即 [文件头+文件数据+数据描述符]{此处可重复n次}+核心目录+目录结束标识 当压缩包中有多个文件时,就会有多个[文件头+文件数据+数据描述符]
2、壓縮與下載步驟
(1)建立壓縮包前準備
//定义压缩包存在服务器的路径 String path = request.getSession().getServletContext().getRealPath("/WEB-INF/fileTemp"); //创建路径 File FilePath = new File(path + "/file"); if (!FilePath.exists()) { FilePath.mkdir(); } String path = FilePath.getPath() + "/"; //定义导出压缩包的名称 String title ="问价压缩包"; //压缩包格式 String fileNamezip = title + ".zip"; String zipPath = path + fileNamezip; //创建一个ZIP输出流并实例化缓冲区域 ZipOutputStream out = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(zipPath))); //设置编码格式(解决linux出现乱码) out.setEncoding("gbk"); //定义字节数组 byte data[] = new byte[2048]; //获取文件记录(获取文件记录代码省略) List FileList =。。。; if (!FileList.isEmpty()) { ExportUtil util = new ExportUtil(title,title, request, response, FilePath.getPath()); }
(2)刪除壓縮包之前的數據,創建壓縮包
util.startZip(FilePath.getPath());
(3)循環將需要壓縮的檔案放到壓縮包中
for (int i = 0; i < FileList.size(); i++) { fileVo fileVo=FileList.get(i); export(fileVo,request,response,title,FilePath.getPath(),fileName); } ------ public void export(fileVo fileVo, HttpServletRequest request, HttpServletResponse response, String title,String path, String fileName) { FileOutputStream fileOutputStream = null; try { File dirFile = null; int i = fileVo.getName().lastIndexOf("."); if(i!=-1){//存在文件类型 fileName1 = fileName1 + "." + (fileVo.getName()).substring(i+1); } boolean bFile = false; String mkdirName = path + File.separatorChar + title; dirFile = new File(mkdirName); if(!dirFile.exists()) { dirFile.getParentFile().mkdirs(); } if (dirFile.isDirectory()) { path = mkdirName + File.separatorChar + fileName1; } else { bFile = dirFile.mkdirs(); } if (bFile) { path = mkdirName + File.separatorChar + fileName1; } fileOutputStream = new FileOutputStream(path.replace("*", "")); String fileName = URLEncoder.encode(fileName1, "UTF-8"); if (fileName.length() > 110) { fileName = new String(fileName1.getBytes("gb2312"), "ISO8859-1"); } response.setHeader("Connection", "close"); response.setHeader("Content-Type", "application/octet-stream"); response.setContentType("application/x-msdownload"); response.setHeader("Content-Disposition", "attachment; filename=\"" + Utf8Util.toUtf8String(fileName) + "\""); //读取文件流输出到到另一个位置 fileVo.getFileIo(fileOutputStream); fileOutputStream.close(); } catch (Exception e) { logger.error("异常:原因如下"+e.getMessage(), e); } finally { try { if (fileOutputStream != null) { fileOutputStream.close(); } } catch (IOException e1) { // TODO Auto-generated catch block logger.error("异常:原因如下"+e1.getMessage(), e1); } } } ------
(4)壓縮完成,關閉輸出流。
util.entdZip(FilePath.getPath());
以上是如何在Java中壓縮檔案並提供下載的詳細內容。更多資訊請關注PHP中文網其他相關文章!