java中压缩文件并下载的实例详解
作者:小妮浅浅 时间:2022-01-01 04:59:12
当我们对一些需要用到的资料进行整理时,会发现文件的内存占用很大,不过是下载或者存储,都不是很方便,这时候我们会想到把文件变成zip格式,即进行压缩。在正式开始压缩和下载文件之前,我们可以先对zip的格式进行一个了解,然后再就具体的方法给大家带来分享。
1、ZIP文件格式
[local file header + file data + data descriptor]{1,n} + central directory + end of central directory record
即
[文件头+文件数据+数据描述符]{此处可重复n次}+核心目录+目录结束标识当压缩包中有多个文件时,就会有多个[文件头+文件数据+数据描述符]
2、压缩和下载步骤
(1)创建压缩包前准备
//定义压缩包存在服务器的路径
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)删除压缩包之前的数据,创建压缩包
util.startZip(FilePath.getPath());
(3)循环将需要压缩的文件放到压缩包中
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)压缩完成,关闭输出流。
util.entdZip(FilePath.getPath());
java生成压缩文件示例代码扩展
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import org.apache.tools.zip.ZipEntry;
import org.apache.tools.zip.ZipOutputStream;
/**
* @project: Test
* @author chenssy
* @date 2013-7-28
* @Description: 文件压缩工具类
* 将指定文件/文件夹压缩成zip、rar压缩文件
*/
public class CompressedFileUtil {
/**
* 默认构造函数
*/
public CompressedFileUtil(){
}
/**
* @desc 将源文件/文件夹生成指定格式的压缩文件,格式zip
* @param resourePath 源文件/文件夹
* @param targetPath 目的压缩文件保存路径
* @return void
* @throws Exception
*/
public void compressedFile(String resourcesPath,String targetPath) throws Exception{
File resourcesFile = new File(resourcesPath); //源文件
File targetFile = new File(targetPath); //目的
//如果目的路径不存在,则新建
if(!targetFile.exists()){
targetFile.mkdirs();
}
String targetName = resourcesFile.getName()+".zip"; //目的压缩文件名
FileOutputStream outputStream = new FileOutputStream(targetPath+"\\"+targetName);
ZipOutputStream out = new ZipOutputStream(new BufferedOutputStream(outputStream));
createCompressedFile(out, resourcesFile, "");
out.close();
}
/**
* @desc 生成压缩文件。
* 如果是文件夹,则使用递归,进行文件遍历、压缩
* 如果是文件,直接压缩
* @param out 输出流
* @param file 目标文件
* @return void
* @throws Exception
*/
public void createCompressedFile(ZipOutputStream out,File file,String dir) throws Exception{
//如果当前的是文件夹,则进行进一步处理
if(file.isDirectory()){
//得到文件列表信息
File[] files = file.listFiles();
//将文件夹添加到下一级打包目录
out.putNextEntry(new ZipEntry(dir+"/"));
dir = dir.length() == 0 ? "" : dir +"/";
//循环将文件夹中的文件打包
for(int i = 0 ; i < files.length ; i++){
createCompressedFile(out, files[i], dir + files[i].getName()); //递归处理
}
}
else{ //当前的是文件,打包处理
//文件输入流
FileInputStream fis = new FileInputStream(file);
out.putNextEntry(new ZipEntry(dir));
//进行写操作
int j = 0;
byte[] buffer = new byte[1024];
while((j = fis.read(buffer)) > 0){
out.write(buffer,0,j);
}
//关闭输入流
fis.close();
}
}
public static void main(String[] args){
CompressedFileUtil compressedFileUtil = new CompressedFileUtil();
try {
compressedFileUtil.compressedFile("G:\\zip", "F:\\zip");
System.out.println("压缩文件已经生成...");
} catch (Exception e) {
System.out.println("压缩文件生成失败...");
e.printStackTrace();
}
}
}
来源:https://www.py.cn/java/download/23821.html
标签:java,压缩文件
0
投稿
猜你喜欢
Java 数组高频考点分析讲解
2021-09-01 13:14:36
详解Java线程同步器CountDownLatch
2023-08-23 18:42:39
SpringBoot文件分片上传的示例代码
2023-06-18 11:30:15
快速学习六大排序算法
2023-11-02 22:36:19
JAVA布局管理器与面板组合代码实例
2022-04-23 15:48:55
Android Studio多渠道打包的配置方法
2023-06-15 23:19:48
Java实现Http工具类的封装操作示例
2021-08-14 10:27:57
Android编程实现WebView添加进度条的方法
2023-07-06 03:16:46
Spring定时任务使用及如何使用邮件监控服务器
2023-01-12 16:38:58
如何查找YUM安装的JAVA_HOME环境变量详解
2023-04-01 11:48:22
springboot创建多module项目的实例
2021-09-09 20:13:20
SpringBoot集成cache缓存的实现
2023-11-27 16:37:39
Java RateLimiter的限流详解
2023-01-06 17:14:12
c语言switch反汇编的实现
2023-06-29 03:38:17
解决maven没有打包xml文件的问题
2023-11-27 14:51:01
Mybatis结果生成键值对的实例代码
2023-11-28 15:50:58
Spring Boot和Kotlin的无缝整合与完美交融
2022-07-08 04:54:09
Java web访问localhost报404错误问题的解决方法
2023-07-27 05:28:55
gson对象序列化的示例
2023-11-25 08:54:28
Springcloud-nacos实现配置和注册中心的方法
2023-06-15 13:46:42