1
|
/**
|
2
|
* Copyright (C) 2015 EDIT
|
3
|
* European Distributed Institute of Taxonomy
|
4
|
* http://www.e-taxonomy.eu
|
5
|
*
|
6
|
* The contents of this file are subject to the Mozilla Public License Version 1.1
|
7
|
* See LICENSE.TXT at the top of this package for the full license terms.
|
8
|
*/
|
9
|
package eu.etaxonomy.cdm.server;
|
10
|
|
11
|
import java.io.BufferedOutputStream;
|
12
|
import java.io.File;
|
13
|
import java.io.FileInputStream;
|
14
|
import java.io.FileOutputStream;
|
15
|
import java.io.IOException;
|
16
|
import java.util.zip.ZipEntry;
|
17
|
import java.util.zip.ZipInputStream;
|
18
|
|
19
|
import org.apache.commons.io.FileUtils;
|
20
|
import org.apache.log4j.Logger;
|
21
|
|
22
|
/**
|
23
|
* This utility extracts files and directories of a standard zip file to
|
24
|
* a destination directory.
|
25
|
* @author www.codejava.net
|
26
|
*
|
27
|
*/
|
28
|
public class UnzipUtility {
|
29
|
|
30
|
|
31
|
private static final Logger logger = Logger.getLogger(UnzipUtility.class);
|
32
|
|
33
|
/**
|
34
|
* Size of the buffer to read/write data
|
35
|
*/
|
36
|
private static final int BUFFER_SIZE = 4096;
|
37
|
/**
|
38
|
* Extracts a zip file specified by the zipFilePath to a directory specified by
|
39
|
* destDirectory (will be created if does not exists)
|
40
|
* @param zipFilePath
|
41
|
* @param destDirectory
|
42
|
* @throws IOException
|
43
|
*/
|
44
|
public void unzip(File zipFile, File destDir) throws IOException {
|
45
|
if (!destDir.exists()) {
|
46
|
destDir.mkdir();
|
47
|
}
|
48
|
String destPath = destDir.getAbsolutePath();
|
49
|
logger.info("unpacking " + zipFile + " into " + destPath);
|
50
|
ZipInputStream zipIn = new ZipInputStream(new FileInputStream(zipFile));
|
51
|
ZipEntry entry = zipIn.getNextEntry();
|
52
|
// iterates over entries in the zip file
|
53
|
while (entry != null) {
|
54
|
String filePath = destPath + File.separator + entry.getName();
|
55
|
if (!entry.isDirectory()) {
|
56
|
// if the entry is a file, extracts it
|
57
|
extractFile(zipIn, filePath);
|
58
|
} else {
|
59
|
// if the entry is a directory, make the directory
|
60
|
File dir = new File(filePath);
|
61
|
dir.mkdir();
|
62
|
}
|
63
|
zipIn.closeEntry();
|
64
|
entry = zipIn.getNextEntry();
|
65
|
}
|
66
|
zipIn.close();
|
67
|
}
|
68
|
/**
|
69
|
* Extracts a zip entry (file entry)
|
70
|
* @param zipIn
|
71
|
* @param filePath
|
72
|
* @throws IOException
|
73
|
*/
|
74
|
private void extractFile(ZipInputStream zipIn, String filePath) throws IOException {
|
75
|
|
76
|
File file = new File(filePath);
|
77
|
FileUtils.forceMkdir(file.getParentFile());
|
78
|
|
79
|
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(filePath));
|
80
|
byte[] bytesIn = new byte[BUFFER_SIZE];
|
81
|
int read = 0;
|
82
|
while ((read = zipIn.read(bytesIn)) != -1) {
|
83
|
bos.write(bytesIn, 0, read);
|
84
|
}
|
85
|
bos.close();
|
86
|
}
|
87
|
}
|