第一次方式是apache的zip包
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-compress</artifactId>
<version>1.16</version>
</dependency>
ZipFile zipFile = null;
int BUFFER_SIZE=1024;
try {
zipFile=new ZipFile(zip);
Enumeration<ZipArchiveEntry> entries = zipFile.getEntries();
ZipArchiveEntry entry = null;
while (entries.hasMoreElements()) {
entry = entries.nextElement();
if (entry.isDirectory()) {
File directory = new File(zipPath, entry.getName());
directory.mkdirs();
} else {
File file = new File(zipPath, entry.getName());
if (!file.getParentFile().exists()) {
file.getParentFile().mkdirs();
}
InputStream is = zipFile.getInputStream(entry);
OutputStream os = new BufferedOutputStream(new FileOutputStream(file), BUFFER_SIZE);
IOUtils.copy(is, os);
IOUtils.closeQuietly(os);
IOUtils.closeQuietly(is);
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
zipFile.close();
} catch (IOException e) {
e.printStackTrace();
}
}
第二种是用zip4j
<dependency>
<groupId>net.lingala.zip4j</groupId>
<artifactId>zip4j</artifactId>
<version>1.3.2</version>
</dependency>
public static void main(String[] args) {
String file1 = "d:\\worktemp\\hfhhByUnitPaper.zip";
String target = "D:\\worktemp";
String password = "password";
try {
ZipFile zipFile = new ZipFile(file1);
if (zipFile.isEncrypted()) {
zipFile.setPassword(password);
}
zipFile.extractAll(target);
} catch (ZipException e) {
e.printStackTrace();
}
}