您的位置:首页 > 编程语言 > Java开发

java spring mvc 下载压缩包简洁代码,读取时候不分段读取。

2016-10-19 14:44 344 查看
java spring mvc 下载压缩包简洁代码,读取时候不分段读取。

package com.juanpi.service.util;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class CustomFileUtil {
private static Logger logger = LoggerFactory.getLogger(CustomFileUtil.class);

public static List<File> getFiles(List<String> filePaths) {
List<File> files = new ArrayList<File>();
if (filePaths == null || filePaths.isEmpty()) {
return null;
}
for (String t : filePaths) {
if (t == null || ("").equals(t)) {
continue;
}
File temp = new File(t);
if (temp.exists()) {
files.add(temp);
}
}
if (files == null || files.isEmpty()) {
return null;
}
return files;
}

/**
* @date 2016-10-18
* @author juanzi
* @param path
* @param fileName
* 创建文件
*/
public static void createFile(String path, String fileName) {
File f = new File(path);
File file = new File(f, fileName);
if (!file.exists()) {
try {
file.createNewFile();
} catch (IOException e) {
logger.error("zipFile createFile error:", e.getMessage(), e);
}
}

}

/**
* 压缩文件列表中的文件
*
* @param files
* @param outputStream
* @throws IOException
*/
public static void zipFile(List<File> files, ZipOutputStream outputStream) {
int size = files.size();
// 压缩列表中的文件
for (int i = 0; i < size; i++) {
File file = (File) files.get(i);
if (file.exists()) {
zipFile(file, outputStream);
}
}
}

/**
* 将文件写入到zip文件中
*
* @param inputFile
* @param outputstream
* @throws Exception
*/
public static void zipFile(File inputFile, ZipOutputStream outputstream) {
FileInputStream inStream = null;
BufferedInputStream bInStream = null;
try {
if (inputFile.isFile()) {
inStream = new FileInputStream(inputFile);
bInStream = new BufferedInputStream(inStream);
ZipEntry entry = new ZipEntry(inputFile.getName());
outputstream.putNextEntry(entry);
byte[] buffer = new byte[2 * 1024 * 1024];
int byteRead = 0;
while ((byteRead = bInStream.read(buffer)) != -1) {
outputstream.write(buffer, 0, byteRead);
}
outputstream.closeEntry(); // Closes the current ZIP entry
}
} catch (IOException e) {
logger.error("zipFile IOException error:", e.getMessage(), e);
} finally {
try {
if (bInStream != null) {
bInStream.close();// 关闭
}
if (inStream != null) {
inStream.close();
}
} catch (IOException e) {
}
}
}

/**
* 下载文件
*
* @param file
* @param response
*/
public static void downloadFile(File file, HttpServletResponse response, boolean isDelete) {
BufferedInputStream fis = null;
OutputStream toClient = null;
try {
// 以流的形式下载文件。
fis = new BufferedInputStream(new FileInputStream(file.getPath()));
// 清空response
response.reset();
toClient = new BufferedOutputStream(response.getOutputStream());
response.setContentType("application/octet-stream");
response.setHeader("Content-Disposition",
"attachment;filename=" + new String(file.getName().getBytes("UTF-8"), "ISO-8859-1"));
byte[] buffer = new byte[1024 * 1024];
int byteRead = 0;
while ((byteRead = fis.read(buffer)) != -1) {
toClient.write(buffer, 0, byteRead);
}
toClient.flush();
if (isDelete) {
file.delete(); // 是否将生成的服务器端文件删除
}
} catch (IOException ex) {
logger.error("compress file error" + ex.getMessage(), ex);
} finally {
try {
if (fis != null) {
fis.close();
}
if (toClient != null) {
toClient.close();
}
} catch (IOException e) {
logger.error("compress file error" + e.getMessage(), e);
}

}
}
}


restful接口如下
/**
* 批量打包下载文件生成zip文件下载
*
* @param session
*/
@CrossOrigin
@RequestMapping(value = "/loadCompressedFolder", method = RequestMethod.GET)
public String downloadFiles(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
ZipOutputStream toClient = null;
FileOutputStream outStream = null;
try {
List<String> filePaths = XXBussess.getAbsolutePaths();
List<File> files = CustomFileUtil.getFiles(filePaths);
if (files == null || files.isEmpty()) {
return "无可下载文件";
}
String fileName = UUID.randomUUID().toString() + ".zip"; // 在服务器端创建打包下载的临时文件
String outFilePath = request.getSession().getServletContext().getRealPath("/");
CustomFileUtil.createFile(outFilePath, fileName);
File file = new File(outFilePath + fileName); // 文件输出流
outStream = new FileOutputStream(file); // 压缩流
toClient = new ZipOutputStream(outStream);
CustomFileUtil.zipFile(files, toClient);
toClient.close();
outStream.close();
CustomFileUtil.downloadFile(file, response, true);
return null;
} catch (Exception e) {
logger.error("loadCompressedFolder error :", e.getMessage(), e);
return "下载失败";
} finally {
if (toClient != null) {
toClient.close();
}
if (outStream != null) {
outStream.close();
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐