如何将文件打成zip包并下载

@FunctionDesc("下载附件")

@RequestMapping(value = "/exportAttachments", method = RequestMethod.GET)

public void exportAttachments(HttpServletResponse response){

try{

//要打包文件所在的文件夹的路径

String filePath = “D:/nt/xsMGR/attachments/”;

File file = new File(filePath);

if(file.isFile()){

System.out.println("文件=="+file.getName()+"不是一个目录 不做处理文件");

}

if(file.isDirectory()){

//给zip命名为123.zip

File zipFile  = new File(file+File.separator+"123.zip");

if(!zipFile.exists()){

System.out.println("开始压缩");

File[]  tempFiles = file.listFiles();

String[] fileNames = new String[tempFiles.length];

for(int j=0;j<tempFiles.length;j++){

fileNames[j] = tempFiles[j].getAbsolutePath();

System.out.println("============"+ fileNames[j]);

}

ZipUtil zipUitl = new ZipUtil();

zipUitl.zipFileAbsolute(fileNames,zipFile.getAbsolutePath());

System.out.println("文件压缩完成");

}else{

System.out.println("压缩文件已存在");

}

// response.reset();

response.setCharacterEncoding("UTF-8");

response.setContentType("application/octet-stream");

//解决中文乱码

String fileName = java.net.URLEncoder.encode("123.zip", "UTF-8");

response.addHeader("Content-Disposition", "attachment; filename=" + fileName);

//获取文件输入流

InputStream in = new FileInputStream(zipFile);

int len = 0;

byte[] buffer = new byte[1024];

while ((len = in.read(buffer)) > 0) {

//将缓冲区的数据输出到客户端浏览器

response.getOutputStream().write(buffer,0,len);

}

in.close();

}

}catch(Exception e){

e.printStackTrace();

}

}

import java.io.BufferedInputStream;

import java.io.BufferedOutputStream;

import java.io.File;

import java.io.FileInputStream;

import java.io.FileNotFoundException;

import java.io.FileOutputStream;

import java.io.IOException;

import java.util.zip.ZipEntry;

import java.util.zip.ZipOutputStream;

import org.apache.log4j.Logger;

public class ZipUtil {

private final Logger log = Logger.getLogger(this.getClass());

private static final int BUFFER = 1024;

public  void zipFileAbsolute (String[] files, String destFile)

{

try

{

BufferedInputStream origin = null;

FileOutputStream dest;

dest = new FileOutputStream(destFile);

ZipOutputStream out = new ZipOutputStream(new BufferedOutputStream(dest));

byte data[] = new byte[BUFFER];

for (int i = 0; i < files.length; i++)

{

FileInputStream fi = new FileInputStream(files[i]);

origin = new BufferedInputStream(fi, BUFFER);

File file=new File(files[i]);

ZipEntry entry = new ZipEntry(file.getName());

out.putNextEntry(entry);

int count;

while ((count = origin.read(data, 0, BUFFER)) != -1)

{

out.write(data, 0, count);

}

origin.close();

// 关闭数据流

fi.close();

}

out.close();

dest.close();

}

catch (FileNotFoundException e)

{

log.error("打包的文件未找到" + e.toString());

}

catch (IOException e)

{

log.error("写入文件时出现异常?!" + e.toString());

}

}

}

(0)

相关推荐