java 下载zip文件并解压
时间: 2024-12-22 19:33:53 浏览: 8
在Java中下载ZIP文件并解压,你可以使用`java.util.zip`包下的`ZipInputStream`和`ZipOutputStream`类来读取和操作压缩文件,以及`FileUtils`类来自Apache Commons IO库来处理文件操作。以下是一个简单的示例:
```java
import org.apache.commons.io.FileUtils;
import java.io.*;
import java.net.URL;
public class DownloadAndExtractZip {
public static void main(String[] args) throws IOException {
// 指定要下载的URL和本地保存的文件名
String url = "http://example.com/path/to/your.zip";
String localPath = "path/to/downloaded.zip";
try (BufferedReader in = new BufferedReader(new InputStreamReader(
new URL(url).openStream(), "UTF-8"));
ZipInputStream zis = new ZipInputStream(in)) {
// 创建目标解压目录
File dir = new File("path/to/extract");
if (!dir.exists()) {
dir.mkdirs();
}
// 解压每个文件到指定目录
ZipEntry entry;
while ((entry = zis.getNextEntry()) != null) {
String zipEntryName = entry.getName();
File destFile = new File(dir, zipEntryName);
// 如果是目录则创建,如果是文件则解压
if (destFile.isDirectory()) {
destFile.mkdirs();
} else {
try (OutputStream out = new FileOutputStream(destFile)) {
byte[] buffer = new byte[1024];
int length;
while ((length = zis.read(buffer)) > 0) {
out.write(buffer, 0, length);
}
}
}
zis.closeEntry(); // 关闭当前条目后继续下一个
}
}
System.out.println("Download and extraction completed.");
//
阅读全文