當我們對一些需要用到的資料進行整理時,會發(fā)現文件的內存占用很大,不過是下載或者存儲,都不是很方便,這時候我們會想到把文件變成zip格式,即進行壓縮。在正式開始壓縮和下載文件之前,我們可以先對zip的格式進行一個了解,然后再就具體的方法給大家?guī)矸窒怼?/p>
1、ZIP文件格式
[local file header + file data + data descriptor]{1,n} + central directory + end of central directory record
即
[文件頭+文件數據+數據描述符]{此處可重復n次}+核心目錄+目錄結束標識當壓縮包中有多個文件時,就會有多個[文件頭+文件數據+數據描述符]
2、壓縮和下載步驟
(1)創(chuàng)建壓縮包前準備
- //定義壓縮包存在服務器的路徑
- 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() + "/";
- //定義導出壓縮包的名稱
- String title ="問價壓縮包";
- //壓縮包格式
- String fileNamezip = title + ".zip";
- String zipPath = path + fileNamezip;
- //創(chuàng)建一個ZIP輸出流并實例化緩沖區(qū)域
- ZipOutputStream out = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(zipPath)));
- //設置編碼格式(解決linux出現亂碼)
- out.setEncoding("gbk");
- //定義字節(jié)數組
- byte data[] = new byte[2048];
- //獲取文件記錄(獲取文件記錄代碼省略)
- List FileList =。。。;
- if (!FileList.isEmpty()) {
- ExportUtil util = new ExportUtil(title,title,
- request, response, FilePath.getPath());
- }
(2)刪除壓縮包之前的數據,創(chuàng)建壓縮包
1
|
util.startZip(FilePath.getPath()); |
(3)循環(huán)將需要壓縮的文件放到壓縮包中
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
|
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)壓縮完成,關閉輸出流。
1
|
util.entdZip(FilePath.getPath()); |
java生成壓縮文件示例代碼擴展
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
|
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 + "/" ; //循環(huán)將文件夾中的文件打包 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中壓縮文件并下載內容請搜索服務器之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持服務器之家!
原文鏈接:https://www.py.cn/java/download/23821.html