-
Notifications
You must be signed in to change notification settings - Fork 27
Expand file tree
/
Copy pathZIP.java
More file actions
71 lines (64 loc) · 2.56 KB
/
ZIP.java
File metadata and controls
71 lines (64 loc) · 2.56 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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
package io.github.biezhi.compress.zip;
import org.apache.commons.compress.archivers.zip.ZipArchiveEntry;
import org.apache.commons.compress.archivers.zip.ZipArchiveInputStream;
import org.apache.commons.compress.archivers.zip.ZipArchiveOutputStream;
import org.apache.commons.compress.utils.IOUtils;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
/**
* ZIP 操作
*
* @author biezhi
* @date 2018/1/16
*/
public class ZIP {
public static void compress(String name, File... files) throws IOException {
try (ZipArchiveOutputStream out = new ZipArchiveOutputStream(new FileOutputStream(name))) {
for (File file : files) {
addToArchiveCompression(out, file, ".");
}
}
}
public static void decompress(String in, File destination) throws IOException {
try (ZipArchiveInputStream jin = new ZipArchiveInputStream(new FileInputStream(in))) {
ZipArchiveEntry entry;
while ((entry = jin.getNextZipEntry()) != null) {
if (entry.isDirectory()) {
continue;
}
File curfile = new File(destination, entry.getName());
if (!curfile.toPath().normalize().startsWith(destination.toPath().normalize())) {
throw new IOException("Bad zip entry");
}
File parent = curfile.getParentFile();
if (!parent.exists()) {
if (!parent.mkdirs()) {
throw new RuntimeException("could not create directory: " + parent.getPath());
}
}
IOUtils.copy(jin, new FileOutputStream(curfile));
}
}
}
private static void addToArchiveCompression(ZipArchiveOutputStream out, File file, String dir) throws IOException {
String name = dir + File.separator + file.getName();
if (file.isFile()) {
ZipArchiveEntry entry = new ZipArchiveEntry(name);
out.putArchiveEntry(entry);
entry.setSize(file.length());
IOUtils.copy(new FileInputStream(file), out);
out.closeArchiveEntry();
} else if (file.isDirectory()) {
File[] children = file.listFiles();
if (children != null) {
for (File child : children) {
addToArchiveCompression(out, child, name);
}
}
} else {
System.out.println(file.getName() + " is not supported");
}
}
}