forked from gooddata/gooddata-java
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathZipUtils.java
More file actions
71 lines (61 loc) · 2.32 KB
/
ZipUtils.java
File metadata and controls
71 lines (61 loc) · 2.32 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 com.gooddata;
import static com.gooddata.Validate.notNull;
import org.springframework.util.StreamUtils;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.file.Path;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
/**
* Utility class for manipulating zip archives.
*/
public abstract class ZipUtils {
/**
* This method compresses the input file to zip format. If the given file is a directory, it recursively
* packs the directory into the output. Not including give directory itself
*
* @param file file to be zipped
* @param output stream where the output will be written
*/
public static void zip(File file, OutputStream output) throws IOException {
zip(file, output, false);
}
/**
* This method compresses the input file to zip format. If the given file is a directory, it recursively
* packs the directory into the output.
*
* @param file file to be zipped
* @param output stream where the output will be written
* @param includeRoot if root dir should be included
*/
public static void zip(File file, OutputStream output, boolean includeRoot) throws IOException {
notNull(file, "file");
notNull(output, "output");
try (ZipOutputStream zos = new ZipOutputStream(output)) {
if (file.isDirectory()) {
zipDir(includeRoot ? file.getParentFile().toPath() : file.toPath(), file, zos);
} else {
zipFile(file.getParentFile().toPath(), file, zos);
}
}
}
private static void zipDir(Path rootPath, File dir, ZipOutputStream zos) throws IOException {
for (File file : notNull(dir.listFiles(), "listed files")) {
if (file.isDirectory()) {
zipDir(rootPath, file, zos);
} else {
zipFile(rootPath, file, zos);
}
}
}
private static void zipFile(Path rootPath, File file, ZipOutputStream zos) throws IOException {
ZipEntry ze = new ZipEntry(rootPath.relativize(file.toPath()).toString());
zos.putNextEntry(ze);
try (FileInputStream fis = new FileInputStream(file)) {
StreamUtils.copy(fis, zos);
}
zos.closeEntry();
}
}