forked from JavaDevTeam/notes
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathjava-io-ZipInputStream.java
More file actions
51 lines (49 loc) · 1.5 KB
/
Copy pathjava-io-ZipInputStream.java
File metadata and controls
51 lines (49 loc) · 1.5 KB
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
---------------------------------
ZipInputStream
---------------------------------
# 解压文件
/**
* 解压文件
* @param file 压缩文件
* @param targetDir 解压文件输出的目录
* @throws IOException
*/
public static void unPacket(Path file, Path targetDir) throws IOException {
if (!Files.exists(targetDir)) {
Files.createDirectories(targetDir);
}
// 创建zip对象
ZipFile zipFile = new ZipFile(file.toFile());
try {
// 读取zip流
try(ZipInputStream zipInputStream = new ZipInputStream(Files.newInputStream(file))){
ZipEntry zipEntry = null;
// 遍历每一个zip项
while ((zipEntry = zipInputStream.getNextEntry()) != null) {
// 获取zip项目名称
String entryName = zipEntry.getName();
// 构建绝对路径
Path entryFile = targetDir.resolve(entryName);
if(zipEntry.isDirectory()) { // 文件夹
if (!Files.isDirectory(entryFile)) {
Files.createDirectories(entryFile);
}
} else { // 文件
// 读取zip项数据流
try(InputStream zipEntryInputStream = zipFile.getInputStream(zipEntry)){
try(OutputStream fileOutputStream = Files.newOutputStream(entryFile, StandardOpenOption.CREATE_NEW)){
byte[] buffer = new byte[4096];
int length = 0;
while ((length = zipEntryInputStream.read(buffer)) != -1) {
fileOutputStream.write(buffer, 0, length);
}
fileOutputStream.flush();
}
}
}
}
}
} finally {
zipFile.close();
}
}