package com.common.util;import org.apache.log4j.Logger;import javax.servlet.http.HttpServletResponse;import java.io.BufferedInputStream;import java.io.BufferedOutputStream;import java.io.ByteArrayInputStream;import java.io.File;import java.io.FileInputStream;import java.io.InputStream;import java.io.OutputStream;import java.net.URLEncoder;import java.util.Map;import java.util.zip.ZipEntry;import java.util.zip.ZipOutputStream;public final class FileUtils { private static final Logger logger = Logger.getLogger(FileUtils.class); //文件下载 public void downLoadFile(HttpServletResponse response,String path) throws Exception { logger.info("path:"+path); File f = new File(path); if (!f.exists()) { response.sendError(404, "File not found!"); return; } String fileName = f.getName(); fileName = new String(fileName.getBytes("UTF-8"), "ISO-8859-1"); BufferedInputStream br = new BufferedInputStream(new FileInputStream(f)); byte[] buf = new byte[1024]; int len = 0; response.reset(); response.setContentType("application/x-msdownload"); response.setHeader("Content-Disposition", "attachment; filename=" + fileName); OutputStream out = response.getOutputStream(); while ((len = br.read(buf)) > 0){ out.write(buf, 0, len); } br.close(); out.close(); } //下载压缩包 public static void downloadZipFileByInputStream(HttpServletResponse response, Map<String,InputStream> map, String zipName) throws Exception{ response.setContentType("application/x-msdownload"); response.setHeader("content-disposition", "attachment;filename="+ URLEncoder.encode(zipName, "utf-8")); ZipOutputStream zos = new ZipOutputStream(response.getOutputStream()); BufferedOutputStream bos = new BufferedOutputStream(zos); for(Map.Entry<String, InputStream> entry : map.entrySet()){ String fileName = entry.getKey(); //每个文件的文件名 InputStream inputStream = entry.getValue(); //每个文件的输入流 BufferedInputStream bis = new BufferedInputStream(inputStream); zos.putNextEntry(new ZipEntry(fileName)); int len = 0; byte[] buf = new byte[10 * 1024]; while( (len=bis.read(buf, 0, buf.length)) != -1){ bos.write(buf, 0, len); } bis.close(); bos.flush(); } bos.close(); } //下载压缩包 public void downloadZipFileByByte(HttpServletResponse response, Map<String, byte[]> files, String zipName) throws Exception{ response.setContentType("application/x-msdownload"); response.setHeader("content-disposition", "attachment;filename="+URLEncoder.encode(zipName, "utf-8")); ZipOutputStream zos = new ZipOutputStream(response.getOutputStream()); BufferedOutputStream bos = new BufferedOutputStream(zos); for(Map.Entry<String, byte[]> entry : files.entrySet()){ String fileName = entry.getKey(); //每个文件的文件名 byte[] file = entry.getValue(); //每个文件的字节 BufferedInputStream bis = new BufferedInputStream(new ByteArrayInputStream(file)); zos.putNextEntry(new ZipEntry(fileName)); int len = 0; byte[] buf = new byte[10 * 1024]; while( (len=bis.read(buf, 0, buf.length)) != -1){ bos.write(buf, 0, len); } bis.close(); bos.flush(); } bos.close(); }}
java文件下载
点赞
收藏