在Java中解压ZIP文件到指定目录可以使用java.util.zip
包中的ZipInputStream
类和ZipEntry
类来实现。下面是一个示例代码:
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
public class UnzipExample {
public static void unzip(String zipFilePath, String destDirectory) throws IOException {
File destDir = new File(destDirectory);
if (!destDir.exists()) {
destDir.mkdir();
}
ZipInputStream zipIn = new ZipInputStream(new FileInputStream(zipFilePath));
ZipEntry entry = zipIn.getNextEntry();
while (entry != null) {
String filePath = destDirectory + File.separator + entry.getName();
if (!entry.isDirectory()) {
extractFile(zipIn, filePath);
} else {
File dir = new File(filePath);
dir.mkdir();
}
zipIn.closeEntry();
entry = zipIn.getNextEntry();
}
zipIn.close();
}
private static void extractFile(ZipInputStream zipIn, String filePath) throws IOException {
try (FileOutputStream fos = new FileOutputStream(filePath)) {
byte[] buffer = new byte[1024];
int length;
while ((length = zipIn.read(buffer)) > 0) {
fos.write(buffer, 0, length);
}
}
}
public static void main(String[] args) {
String zipFilePath = "example.zip";
String destDirectory = "unzipped";
try {
unzip(zipFilePath, destDirectory);
System.out.println("ZIP file has been successfully extracted to " + destDirectory);
} catch (IOException e) {
System.out.println("Error occurred during ZIP file extraction: " + e.getMessage());
}
}
}
在上面的示例代码中,unzip
方法接收ZIP文件的路径和目标目录的路径作为参数,然后使用ZipInputStream
类逐个解析ZIP文件中的条目,并根据条目的类型(文件或目录)进行解压操作。解压文件时,调用extractFile
方法来将文件内容写入到目标目录中。最后,在main
方法中调用unzip
方法来解压ZIP文件到指定目录。