Home >Java >javaTutorial >How to compress a file in Java and provide it for download

How to compress a file in Java and provide it for download

王林
王林forward
2023-04-21 17:13:083314browse

1. ZIP file format

[local file header + file data + data descriptor]{1,n} + central directory + end of central directory record
即
[文件头+文件数据+数据描述符]{此处可重复n次}+核心目录+目录结束标识
 
当压缩包中有多个文件时,就会有多个[文件头+文件数据+数据描述符]

2. Compression and download steps

(1) Create compression Preparation before package

//定义压缩包存在服务器的路径
String path = request.getSession().getServletContext().getRealPath("/WEB-INF/fileTemp");
//创建路径
File FilePath = new File(path + "/file");
if (!FilePath.exists()) {
FilePath.mkdir();
}
String path = FilePath.getPath() + "/";
//定义导出压缩包的名称
String title ="问价压缩包";
//压缩包格式
String fileNamezip = title + ".zip";
String zipPath = path + fileNamezip;
//创建一个ZIP输出流并实例化缓冲区域
ZipOutputStream out = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(zipPath)));
//设置编码格式(解决linux出现乱码)
out.setEncoding("gbk");
//定义字节数组
byte data[] = new byte[2048];
 
//获取文件记录(获取文件记录代码省略)
List FileList =。。。;
if (!FileList.isEmpty()) {
ExportUtil util = new ExportUtil(title,title,
request, response, FilePath.getPath());
}

(2) Delete the data before the compressed package and create the compressed package

util.startZip(FilePath.getPath());

(3) Loop the files that need to be compressed into the compressed package

for (int i = 0; i < FileList.size(); i++) {
fileVo fileVo=FileList.get(i);
export(fileVo,request,response,title,FilePath.getPath(),fileName);
}
------
public void export(fileVo fileVo, HttpServletRequest request,
HttpServletResponse response, String title,String path, String fileName) {
FileOutputStream fileOutputStream = null;
try {
File dirFile = null;  
int i = fileVo.getName().lastIndexOf(".");
        if(i!=-1){//存在文件类型
         fileName1 = fileName1 + "." +  (fileVo.getName()).substring(i+1);
        }
boolean bFile = false;
String mkdirName = path + File.separatorChar + title;
dirFile = new File(mkdirName);
if(!dirFile.exists()) {
dirFile.getParentFile().mkdirs();
}
if (dirFile.isDirectory()) {
path = mkdirName + File.separatorChar + fileName1;
} else {
bFile = dirFile.mkdirs();
}
if (bFile) {
path = mkdirName + File.separatorChar + fileName1;
}  
fileOutputStream = new FileOutputStream(path.replace("*", ""));  
String fileName = URLEncoder.encode(fileName1, "UTF-8");
if (fileName.length() > 110) {
fileName = new String(fileName1.getBytes("gb2312"), "ISO8859-1");
}
response.setHeader("Connection", "close");
response.setHeader("Content-Type", "application/octet-stream");
response.setContentType("application/x-msdownload");
response.setHeader("Content-Disposition", "attachment; filename=\""
+ Utf8Util.toUtf8String(fileName) + "\"");
//读取文件流输出到到另一个位置
fileVo.getFileIo(fileOutputStream);
fileOutputStream.close();  
} catch (Exception e) {
logger.error("异常:原因如下"+e.getMessage(), e);
} finally {
try {
if (fileOutputStream != null) {
fileOutputStream.close();
}
} catch (IOException e1) {
// TODO Auto-generated catch block
logger.error("异常:原因如下"+e1.getMessage(), e1);
}
}
}
------

(4) The compression is completed and the output stream is closed.

util.entdZip(FilePath.getPath());

The above is the detailed content of How to compress a file in Java and provide it for download. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:yisu.com. If there is any infringement, please contact admin@php.cn delete