java中壓縮文件并下載的實例詳解
當我們對一些需要用到的資料進行整理時,會發現文件的內存占用很大,不過是下載或者存儲,都不是很方便,這時候我們會想到把文件變成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 blocklogger.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();} }}
到此這篇關于java中壓縮文件并下載的實例詳解的文章就介紹到這了,更多相關如何在java中壓縮文件并下載內容請搜索好吧啦網以前的文章或繼續瀏覽下面的相關文章希望大家以后多多支持好吧啦網!
相關文章: