java中压缩文件并下载的实例详解
当我们对一些需要用到的资料进行整理时,会发现文件的内存占用很大,不过是下载或者存储,都不是很方便,这时候我们会想到把文件变成zip格式,即进行压缩。在正式开始压缩和下载文件之前,我们可以先对zip的格式进行一个了解,然后再就具体的方法给大家带来分享。
1、ZIP文件格式
[localfileheader+filedata+datadescriptor]{1,n}+centraldirectory+endofcentraldirectoryrecord
即
[文件头+文件数据+数据描述符]{此处可重复n次}+核心目录+目录结束标识当压缩包中有多个文件时,就会有多个[文件头+文件数据+数据描述符]
2、压缩和下载步骤
(1)创建压缩包前准备
//定义压缩包存在服务器的路径
Stringpath=request.getSession().getServletContext().getRealPath("/WEB-INF/fileTemp");
//创建路径
FileFilePath=newFile(path+"/file");
if(!FilePath.exists()){
FilePath.mkdir();
}
Stringpath=FilePath.getPath()+"/";
//定义导出压缩包的名称
Stringtitle="问价压缩包";
//压缩包格式
StringfileNamezip=title+".zip";
StringzipPath=path+fileNamezip;
//创建一个ZIP输出流并实例化缓冲区域
ZipOutputStreamout=newZipOutputStream(newBufferedOutputStream(newFileOutputStream(zipPath)));
//设置编码格式(解决linux出现乱码)
out.setEncoding("gbk");
//定义字节数组
bytedata[]=newbyte[2048];
//获取文件记录(获取文件记录代码省略)
ListFileList=。。。;
if(!FileList.isEmpty()){
ExportUtilutil=newExportUtil(title,title,
request,response,FilePath.getPath());
}
(2)删除压缩包之前的数据,创建压缩包
util.startZip(FilePath.getPath());
(3)循环将需要压缩的文件放到压缩包中
for(inti=0;i110){ fileName=newString(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(Exceptione){ logger.error("异常:原因如下"+e.getMessage(),e); }finally{ try{ if(fileOutputStream!=null){ fileOutputStream.close(); } }catch(IOExceptione1){ //TODOAuto-generatedcatchblock logger.error("异常:原因如下"+e1.getMessage(),e1); } } }
(4)压缩完成,关闭输出流。
util.entdZip(FilePath.getPath());
java生成压缩文件示例代码扩展
importjava.io.BufferedOutputStream;
importjava.io.File;
importjava.io.FileInputStream;
importjava.io.FileOutputStream;
importorg.apache.tools.zip.ZipEntry;
importorg.apache.tools.zip.ZipOutputStream;
/**
*@project:Test
*@authorchenssy
*@date2013-7-28
*@Description:文件压缩工具类
* 将指定文件/文件夹压缩成zip、rar压缩文件
*/
publicclassCompressedFileUtil{
/**
*默认构造函数
*/
publicCompressedFileUtil(){
}
/**
*@desc将源文件/文件夹生成指定格式的压缩文件,格式zip
*@paramresourePath源文件/文件夹
*@paramtargetPath 目的压缩文件保存路径
*@returnvoid
*@throwsException
*/
publicvoidcompressedFile(StringresourcesPath,StringtargetPath)throwsException{
FileresourcesFile=newFile(resourcesPath); //源文件
FiletargetFile=newFile(targetPath); //目的
//如果目的路径不存在,则新建
if(!targetFile.exists()){
targetFile.mkdirs();
}
StringtargetName=resourcesFile.getName()+".zip"; //目的压缩文件名
FileOutputStreamoutputStream=newFileOutputStream(targetPath+"\\"+targetName);
ZipOutputStreamout=newZipOutputStream(newBufferedOutputStream(outputStream));
createCompressedFile(out,resourcesFile,"");
out.close();
}
/**
*@desc生成压缩文件。
* 如果是文件夹,则使用递归,进行文件遍历、压缩
* 如果是文件,直接压缩
*@paramout 输出流
*@paramfile 目标文件
*@returnvoid
*@throwsException
*/
publicvoidcreateCompressedFile(ZipOutputStreamout,Filefile,Stringdir)throwsException{
//如果当前的是文件夹,则进行进一步处理
if(file.isDirectory()){
//得到文件列表信息
File[]files=file.listFiles();
//将文件夹添加到下一级打包目录
out.putNextEntry(newZipEntry(dir+"/"));
dir=dir.length()==0?"":dir+"/";
//循环将文件夹中的文件打包
for(inti=0;i0){
out.write(buffer,0,j);
}
//关闭输入流
fis.close();
}
}
publicstaticvoidmain(String[]args){
CompressedFileUtilcompressedFileUtil=newCompressedFileUtil();
try{
compressedFileUtil.compressedFile("G:\\zip","F:\\zip");
System.out.println("压缩文件已经生成...");
}catch(Exceptione){
System.out.println("压缩文件生成失败...");
e.printStackTrace();
}
}
}
到此这篇关于java中压缩文件并下载的实例详解的文章就介绍到这了,更多相关如何在java中压缩文件并下载内容请搜索毛票票以前的文章或继续浏览下面的相关文章希望大家以后多多支持毛票票!