在工作過程中,需要將一個文件夾生成壓縮文件,然后提供給用戶下載。所以自己寫了一個壓縮文件的工具類。該工具類支持單個文件和文件夾壓縮。放代碼:
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
|
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.util下的java.util.zip進行打包處理,可能會出現中文亂碼問題,這是因為java的zip方法不支持編碼格式的更改,我們可以使用ant.java下的zip工具類來進行打包處理。所以需要將ant.jar導入項目的lib目錄下。
總結
以上所述是小編給大家介紹的java生成壓縮文件的實例代碼,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復大家的。在此也非常感謝大家對服務器之家網站的支持!
原文鏈接:https://www.cnblogs.com/chenssy/p/3223902.html