使用org.apache.tools.zip.ZipOutputStream
壓縮
import java.io.*; import java.text.SimpleDateFormat; import java.util.Date; import java.util.zip.ZipEntry; import java.util.zip.ZipOutputStream; public class CompressZip { public static void ZipCompress(String inputFile, String outputFile) throws Exception { //創建zip輸出流 ZipOutputStream out = new ZipOutputStream(new FileOutputStream(outputFile)); //創建緩沖輸出流 BufferedOutputStream bos = new BufferedOutputStream(out); File input = new File(inputFile); if (input.isDirectory()) { //取出文件夾中的文件(或子文件夾) File[] flist = input.listFiles(); if (flist.length >0){ for (int i = 0; i < flist.length; i++) { compress(out, bos, flist[i], null); } } } bos.close(); out.close(); } /** * @param name 壓縮文件名,可以寫為null保持默認 */ //遞歸壓縮 public static void compress(ZipOutputStream out, BufferedOutputStream bos, File input, String name) throws IOException { if (name == null) { name = input.getName(); } bos.flush(); //如果路徑為目錄(文件夾) if (input.isDirectory()) { //取出文件夾中的文件(或子文件夾) File[] flist = input.listFiles(); if (flist.length == 0)//如果文件夾為空,則只需在目的地zip文件中寫入一個目錄進入 { out.putNextEntry(new ZipEntry(name + "/")); } else//如果文件夾不為空,則遞歸調用compress,文件夾中的每一個文件(或文件夾)進行壓縮 { for (int i = 0; i < flist.length; i++) { compress(out, bos, flist[i], name + "/" + flist[i].getName()); } } } else//如果不是目錄(文件夾),即為文件,則先寫入目錄進入點,之后將文件寫入zip文件中 { out.putNextEntry(new ZipEntry(name)); FileInputStream fos = new FileInputStream(input); BufferedInputStream bis = new BufferedInputStream(fos); int len; //將源文件寫入到zip文件中 byte[] buf = new byte[1024]; while ((len = bis.read(buf)) != -1) { bos.write(buf,0,len); } bis.close(); fos.close(); } } public static void main(String[] args) { try { String path = "E:\\data\\down"; String fileName = "data" + new SimpleDateFormat("yyyyMMddHHmmss").format(new Date())+".zip"; ZipCompress(path, "E:\\data\\test\\"+fileName); } catch (Exception e) { e.printStackTrace(); } } }
下載
@RequestMapping("/downloadZip") public void downloadZip(HttpServletRequest req, HttpServletResponse resp, String name) { try { // path是指欲下載的文件的路徑。 File file = new File("E:\\data\\test\\"+name+".zip"); // 取得文件名。 String filename = file.getName(); String ext = filename.substring(filename.lastIndexOf(".") + 1).toUpperCase(); InputStream fis = new BufferedInputStream(new FileInputStream(file)); byte[] buffer = new byte[fis.available()]; fis.read(buffer); fis.close(); // 清空response resp.reset(); // 設置response的Header resp.addHeader("Content-Disposition", "attachment;filename=" + new String(filename.getBytes())); resp.addHeader("Content-Length", "" + file.length()); OutputStream toClient = new BufferedOutputStream(resp.getOutputStream()); resp.setContentType("application/octet-stream"); toClient.write(buffer); toClient.flush(); toClient.close(); } catch (IOException ex) { ex.printStackTrace(); } }