java中壓縮文件并下載的實(shí)例詳解
當(dāng)我們對(duì)一些需要用到的資料進(jìn)行整理時(shí),會(huì)發(fā)現(xiàn)文件的內(nèi)存占用很大,不過是下載或者存儲(chǔ),都不是很方便,這時(shí)候我們會(huì)想到把文件變成zip格式,即進(jìn)行壓縮。在正式開始?jí)嚎s和下載文件之前,我們可以先對(duì)zip的格式進(jìn)行一個(gè)了解,然后再就具體的方法給大家?guī)矸窒怼?/p>1、ZIP文件格式
[local file header + file data + data descriptor]{1,n} + central directory + end of central directory record即[文件頭+文件數(shù)據(jù)+數(shù)據(jù)描述符]{此處可重復(fù)n次}+核心目錄+目錄結(jié)束標(biāo)識(shí)當(dāng)壓縮包中有多個(gè)文件時(shí),就會(huì)有多個(gè)[文件頭+文件數(shù)據(jù)+數(shù)據(jù)描述符]
2、壓縮和下載步驟(1)創(chuàng)建壓縮包前準(zhǔn)備
//定義壓縮包存在服務(wù)器的路徑String path = request.getSession().getServletContext().getRealPath('/WEB-INF/fileTemp');//創(chuàng)建路徑File FilePath = new File(path + '/file');if (!FilePath.exists()) {FilePath.mkdir();}String path = FilePath.getPath() + '/';//定義導(dǎo)出壓縮包的名稱String title ='問價(jià)壓縮包';//壓縮包格式String fileNamezip = title + '.zip';String zipPath = path + fileNamezip;//創(chuàng)建一個(gè)ZIP輸出流并實(shí)例化緩沖區(qū)域ZipOutputStream out = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(zipPath)));//設(shè)置編碼格式(解決linux出現(xiàn)亂碼)out.setEncoding('gbk');//定義字節(jié)數(shù)組byte data[] = new byte[2048];//獲取文件記錄(獲取文件記錄代碼省略)List FileList =。。。;if (!FileList.isEmpty()) {ExportUtil util = new ExportUtil(title,title,request, response, FilePath.getPath());}
(2)刪除壓縮包之前的數(shù)據(jù),創(chuàng)建壓縮包
util.startZip(FilePath.getPath());
(3)循環(huán)將需要壓縮的文件放到壓縮包中
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) + ''');//讀取文件流輸出到到另一個(gè)位置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 blocklogger.error('異常:原因如下'+e1.getMessage(), e1);}}}
(4)壓縮完成,關(guān)閉輸出流。
util.entdZip(FilePath.getPath());
java生成壓縮文件示例代碼擴(kuò)展
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 { /** * 默認(rèn)構(gòu)造函數(shù) */ 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 生成壓縮文件。 * 如果是文件夾,則使用遞歸,進(jìn)行文件遍歷、壓縮 * 如果是文件,直接壓縮 * @param out 輸出流 * @param file 目標(biāo)文件 * @return void * @throws Exception */ public void createCompressedFile(ZipOutputStream out,File file,String dir) throws Exception{//如果當(dāng)前的是文件夾,則進(jìn)行進(jìn)一步處理if(file.isDirectory()){ //得到文件列表信息 File[] files = file.listFiles(); //將文件夾添加到下一級(jí)打包目錄 out.putNextEntry(new ZipEntry(dir+'/')); dir = dir.length() == 0 ? '' : dir +'/'; //循環(huán)將文件夾中的文件打包 for(int i = 0 ; i < files.length ; i++){createCompressedFile(out, files[i], dir + files[i].getName()); //遞歸處理 }}else{ //當(dāng)前的是文件,打包處理 //文件輸入流 FileInputStream fis = new FileInputStream(file); out.putNextEntry(new ZipEntry(dir)); //進(jìn)行寫操作 int j = 0; byte[] buffer = new byte[1024]; while((j = fis.read(buffer)) > 0){out.write(buffer,0,j); } //關(guān)閉輸入流 fis.close();} } public static void main(String[] args){CompressedFileUtil compressedFileUtil = new CompressedFileUtil();try { compressedFileUtil.compressedFile('G:zip', 'F:zip'); System.out.println('壓縮文件已經(jīng)生成...');} catch (Exception e) { System.out.println('壓縮文件生成失敗...'); e.printStackTrace();} }}
到此這篇關(guān)于java中壓縮文件并下載的實(shí)例詳解的文章就介紹到這了,更多相關(guān)如何在java中壓縮文件并下載內(nèi)容請(qǐng)搜索好吧啦網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持好吧啦網(wǎng)!
相關(guān)文章:
1. Python文本文件的合并操作方法代碼實(shí)例2. windows服務(wù)器使用IIS時(shí)thinkphp搜索中文無效問題3. asp讀取xml文件和記數(shù)4. Python sorted排序方法如何實(shí)現(xiàn)5. ASP.NET MVC實(shí)現(xiàn)橫向展示購(gòu)物車6. 每日六道java新手入門面試題,通往自由的道路第二天7. Python 中如何使用 virtualenv 管理虛擬環(huán)境8. python利用opencv實(shí)現(xiàn)顏色檢測(cè)9. CSS自定義滾動(dòng)條樣式案例詳解10. PHP實(shí)現(xiàn)基本留言板功能原理與步驟詳解
