本文實例講述了Java創建ZIP壓縮文件的方法。分享給大家供大家參考。具體如下:
這里注意:建議使用org.apache.tools.zip.*包下相關類,否則可能會出現中文亂碼問題。
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
|
/** * 壓縮文件夾 * @param sourceDIR 文件夾名稱(包含路徑) * @param targetZipFile 生成zip文件名 * @author liuxiangwei */ public static void zipDIR(String sourceDIR, String targetZipFile) { try { FileOutputStream target = new FileOutputStream(targetZipFile); ZipOutputStream out = new ZipOutputStream( new BufferedOutputStream(target)); int BUFFER_SIZE = 1024 ; byte buff[] = new byte [BUFFER_SIZE]; File dir = new File(sourceDIR); if (!dir.isDirectory()) { throw new IllegalArgumentException(sourceDIR+ " is not a directory!" ); } File files[] = dir.listFiles(); for ( int i = 0 ; i < files.length; i++) { FileInputStream fi = new FileInputStream(files[i]); BufferedInputStream origin = new BufferedInputStream(fi); ZipEntry entry = new ZipEntry(files[i].getName()); out.putNextEntry(entry); int count; while ((count = origin.read(buff)) != - 1 ) { out.write(buff, 0 , count); } origin.close(); } out.close(); } catch (IOException e) { throw new MsgException( "" ); } } |
希望本文所述對大家的java程序設計有所幫助。