java压缩文件并下载

废话不多说,贴代码

response.setHeader("content-type", "application/octet-stream");
        //response.setContentType("application/gorce-download");
        response.setContentType("application/octet-stream");
        response.addHeader("Content-disposition", "attachment;fileName=" + (URLEncoder.encode("sample.zip", "UTF-8")) + "");
        File zipFile = new File(filePath+loginCacheManage.getUserName()+"\\temp.zip");
        byte[] buf = new byte[1024];
        int len;
        ZipOutputStream zout = new ZipOutputStream(new FileOutputStream(zipFile));
        for (String name : filename) {
            File file = new File(filePath + loginCacheManage.getUserName() + "/" + name);
            FileInputStream input1 = new FileInputStream(file);

            FileInputStream in = input1;
            zout.putNextEntry(new ZipEntry(name));
            while ((len = in.read(buf)) > 0) {
                zout.write(buf, 0, len);
            }
            zout.closeEntry();
            in.close();
        }
        zout.close();
        OutputStream out = response.getOutputStream();
        FileInputStream zipInput =new FileInputStream(zipFile);
        while ((len=zipInput.read(buf))!= -1){
            out.write(buf,0,len);
        }
        zipInput.close();
        out.flush();
        out.close();
        //删除压缩包
        zipFile.delete();

 

你可能感兴趣的:(java,zip,压缩文件,java)