-
Notifications
You must be signed in to change notification settings - Fork 27
Expand file tree
/
Copy pathJAR.java
More file actions
72 lines (65 loc) · 2.58 KB
/
JAR.java
File metadata and controls
72 lines (65 loc) · 2.58 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
72
package io.github.biezhi.compress.jar;
import org.apache.commons.compress.archivers.jar.JarArchiveEntry;
import org.apache.commons.compress.archivers.jar.JarArchiveInputStream;
import org.apache.commons.compress.archivers.jar.JarArchiveOutputStream;
import org.apache.commons.compress.utils.IOUtils;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
/**
* JAR 操作
*
* @author biezhi
* @date 2018/1/16
*/
public class JAR {
private JAR() {}
public static void compress(String name, File... files) throws IOException {
try (JarArchiveOutputStream out = new JarArchiveOutputStream(new FileOutputStream(name))) {
for (File file : files) {
addToArchiveCompression(out, file, ".");
}
}
}
public static void decompress(String in, File destination) throws IOException {
try (JarArchiveInputStream jin = new JarArchiveInputStream(new FileInputStream(in))) {
JarArchiveEntry entry;
while ((entry = jin.getNextJarEntry()) != 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(JarArchiveOutputStream out, File file, String dir) throws IOException {
String name = dir + File.separator + file.getName();
if (file.isFile()) {
JarArchiveEntry entry = new JarArchiveEntry(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");
}
}
}