JDK自带了zip相关的api,但遗憾的是,如果zip文件中有包含中文名的文件,就报错无法处理,所以,我这里的例子并没有用jdk的api,而是用了apache的ant包。
apache ant下载地址:
http://ant.apache.org/bindownload.cgi
把lib/ant.jar放到我们项目的构建路径中,只需要ant.jar。其实ant的zip API与jdk的高度相似,如果之前是用jdk的api写的,基本上只要更改顶部的import包就可以了
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
97
| package common;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.Enumeration;
import java.util.List;
import org.apache.tools.zip.ZipEntry;
import org.apache.tools.zip.ZipFile;
import org.apache.tools.zip.ZipOutputStream;
public class ZipUtils {
public static void main(String[] args) throws Exception {
unzipPSD("/media/share/material/file/temp/1eeb28ecb8e0d6f2.zip","/media/share/material/file/temp/");
}
/**
* 解压zip,
*
* @param zipFile 里面可以有多个psd文件,支持多级目录
* @param targetPath 保存目录
* @throws Exception
*/
public static void unzipPSD(String zipPath, String targetPath) throws Exception {
ZipFile zipFile = new ZipFile(zipPath);
Enumeration emu = zipFile.getEntries();
int i = 0;
while (emu.hasMoreElements()) {
ZipEntry entry = (ZipEntry) emu.nextElement();
String fileName=entry.getName().toLowerCase();
if(!fileName.startsWith("__macosx/")&&fileName.endsWith("psd"))
{
//如果文件名没有以__macosx/开头,且以psd结尾,就是psd文件,解压,在mac下压缩的文件,会自动加上__macosx目录,但其实是没用的
BufferedInputStream bis = new BufferedInputStream(
zipFile.getInputStream(entry));
File file = new File(targetPath + System.currentTimeMillis()+".psd");
//一次读40K
int BUFFER=40960;
FileOutputStream fos = new FileOutputStream(file);
BufferedOutputStream bos = new BufferedOutputStream(fos, BUFFER);
int count;
byte data[] = new byte[BUFFER];
while ((count = bis.read(data, 0, BUFFER)) != -1) {
bos.write(data, 0, count);
}
bos.flush();
bos.close();
bis.close();
}
}
zipFile.close();
}
/**
* 压缩多个文件
* @param zipPath
* @param filePaths
*/
public static void zipFiles(String zipPath,List filePaths)
{
try {
BufferedInputStream origin = null;
FileOutputStream dest = new FileOutputStream(zipPath);
ZipOutputStream out = new ZipOutputStream(new BufferedOutputStream(
dest));
int BUFFER=40960;
byte data[] = new byte[BUFFER];
for(String filePah:filePaths)
{
File file=new File(filePah);
FileInputStream fi = new FileInputStream(file);
origin = new BufferedInputStream(fi, BUFFER);
ZipEntry entry = new ZipEntry(file.getName());
out.putNextEntry(entry);
int count;
while ((count = origin.read(data, 0, BUFFER)) != -1) {
out.write(data, 0, count);
}
origin.close();
}
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}
} |
© 2013, 冰冻鱼. 请尊重作者劳动成果,复制转载保留本站链接! 应用开发笔记