在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文件到指定目錄。