近来项目中需要对ZIP压缩包解压,然后将解压后的内容存放到指定的目录下。
该压缩包的特性:
- 使用标准的zip压缩格式(压缩算法没有深入探究)
- 压缩包中带有目录并且目录名称是中文
- 压缩时加了密码
因为jre中自带的java.util.zip.*包不支持中文及加密压缩,所以选择使用zip4j包。
下面是解压的实现代码:
1 public class UnZip {
2 private final int BUFF_SIZE = 4096;
3
4 /*
5 获取ZIP文件中的文件名和目录名
6 */
7 public void getEntryNames(String zipFilePath, String password){
8 List<String> entryList = new ArrayList<String>();
9 ZipFile zf;
10 try {
11 zf = new ZipFile(zipFilePath);
12 zf.setFileNameCharset("gbk");//默认UTF8,如果压缩包中的文件名是GBK会出现乱码
13 if(zf.isEncrypted()){
14 zf.setPassword(password);//设置压缩密码
15 }
16 for(Object obj : zf.getFileHeaders()){
17 FileHeader fileHeader = (FileHeader)obj;
18 String fileName = fileHeader.getFileName();//文件名会带上层级目录信息
19 entryList.add(fileName);
20 }
21 } catch (ZipException e) {
22 e.printStackTrace();
23 }
24 return entryList;
25 }
26
27 /*
28 将ZIP包中的文件解压到指定目录
29 */
30 public void extract(String zipFilePath, String password, String destDir){
31 InputStream is = null;
32 OutputStream os = null;
33 ZipFile zf;
34 try {
35 zf = new ZipFile(zipFile);
36 zf.setFileNameCharset("gbk");
37 if(zf.isEncrypted()){
38 zf.setPassword(PASSWORD);
39 }
40
41 for(Object obj : zf.getFileHeaders()){
42 FileHeader fileHeader = (FileHeader)obj;
43 String destFile = destDir + "/" + fileHeader.getFileName();
44 if(!destFile.getParentFile().exists()){
45 destFile.getParentFile().mkdirs();//创建目录
46 }
47 is = zf.getInputStream(fileHeader);
48 os = new FileOutputStream(destFile);
49 int readLen = -1;
50 byte[] buff = new byte[BUFF_SIZE];
51 while ((readLen = is.read(buff)) != -1) {
52 os.write(buff, 0, readLen);
53 }
54 }
55 }catch(Exception e){
56 e.printStackTrace();
57 }finally{
58 //关闭资源
59 try{
60 if(is != null){
61 is.close();
62 }
63 }catch(IOException ioe){}
64
65 try{
66 if(os != null){
67 os.close();
68 }
69 }catch(IOException ioe){}
70 }
71 }
72 }
以上代码未经测试,仅作为伪代码参考