import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Enumeration;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
public class ZipUtil {
/**
* 解压zip文件到指定目录
*
* @param zipFilePath zip文件的路径
* @param destDir 解压到的目标目录
*/
public static void unzip(String zipFilePath, String destDir) {
FileInputStream fis = null;
ZipFile zipFile = null;
try {
fis = new FileInputStream(zipFilePath);
zipFile = new ZipFile(fis);
Enumeration<? extends ZipEntry> entries = zipFile.entries();
while (entries.hasMoreElements()) {
ZipEntry entry = entries.nextElement();
String filePath = destDir + File.separator + entry.getName();
if (!entry.isDirectory()) {
// 如果不是目录,则解压文件
extractFile(zipFile, entry, filePath);
} else {
// 如果是目录,则创建目录
File dir = new File(filePath);
dir.mkdirs();
}
}
fis.close();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (zipFile != null) {
try {
zipFile.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (fis != null) {
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
/**
* 解压zip中的文件
*
* @param zipFile zip文件
* @param zipEntry zip条目
* @param filePath 文件解压后的路径
*/
private static void extractFile(ZipFile zipFile, ZipEntry zipEntry, String filePath) {
BufferedOutputStream bos = null;
try {
FileOutputStream fos = new FileOutputStream(filePath);
bos = new BufferedOutputStream(fos);
byte[] bytesIn = new byte[4096];
int read = 0;
InputStream zis = zipFile.getInputStream(zipEntry);
while ((read = zis.read(bytesIn)) != -1) {
bos.write(bytesIn, 0, read);
}
bos.flush();
bos.close();
zis.close();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (bos != null) {
try {
bos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
public static void main(String[] args) {
String zipFilePath = "path/to/your/zipfile.zip";
String destDir = "path/to/destination/directory";
unzip(zipFilePath, destDir);
}
}
这段代码展示了如何在Java中解压一个zip文件到指定的目录。注意,这个示例使用了`java.util.zip`包中的类。在实际使用中,你需要将`zipFilePath`和`destDir`替换为你的zip文件路径和解压目标目录。