本例以Windows, JDK1.7 为基础,来演示使用Java 解压ZIP格式的文件。

在API中有java.util.zip可以用来压缩ZIP格式的文件,主要使用FileOutputStream, ZipInputStream, FileInputStream, ZipEntry 类.

演示逻辑:
读取”D:\Person-Test\test.zip”的压缩文件,解压到”D:\Person-Test\temp"路径下面。

解压ZIP格式文件

DecompressFileFromZip.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
package com.devnp.zip;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;

public class DecompressFileFromZip {

public static void main(String[] args) {
// TODO Auto-generated method stub
String outFolder = "D:\\Person-Test\\temp\\" ;

File zipFile = new File("D:\\Person-Test\\test.zip");

decompressFile(zipFile, outFolder);
}

public static void decompressFile(File zipFile, String outFolder) {
ZipInputStream zis = null;
ZipEntry ze = null;

try {
zis = new ZipInputStream(new FileInputStream(zipFile));

//list all file
while ((ze = zis.getNextEntry()) != null) {
String fileName = ze.getName();

File file = new File(outFolder + File.separator + fileName);

new File(file.getParent()).mkdirs(); //创建文件夹,如果不存

System.out.println("File Name : " + fileName);

FileOutputStream fos = new FileOutputStream(file);

byte[] buffer = new byte[1024];
int len;
while ((len = zis.read(buffer)) > 0) {
fos.write(buffer, 0, len);
}

fos.close();

}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
try {
if(zis != null)
zis.close();
} catch (IOException e) {
// TODO: handle exception
}
}

System.out.println("Decompression From Zip is Success.");
}

}
运行结果:
1
2
3
4
5
6
File Name : 1\1.txt
File Name : 2\3\New Text Document.txt
File Name : 2.txt
File Name : 5.pdf
File Name : sudent.txt
Decompression From Zip is Success.

相关

关于如何压缩成ZIP格式的文件 : JAVA FILE COMPRESSION 压缩ZIP格式的文件