Java解压多层zip包并保存
时间: 2023-06-28 19:07:41 浏览: 56
你可以使用Java的ZipInputStream类进行多层zip包的解压缩,然后使用FileOutputStream类将解压后的文件保存到本地磁盘。
以下是一个简单的示例代码:
```java
import java.io.*;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
public class UnzipDemo {
public static void main(String[] args) {
String zipFilePath = "path/to/your/zip/file.zip";
String destFolderPath = "path/to/save/unzipped/files";
unzip(zipFilePath, destFolderPath);
}
public static void unzip(String zipFilePath, String destFolderPath) {
try {
FileInputStream fis = new FileInputStream(zipFilePath);
ZipInputStream zis = new ZipInputStream(fis);
ZipEntry zipEntry;
while ((zipEntry = zis.getNextEntry()) != null) {
String fileName = zipEntry.getName();
File newFile = new File(destFolderPath + File.separator + fileName);
// create all non-existent folders
new File(newFile.getParent()).mkdirs();
FileOutputStream fos = new FileOutputStream(newFile);
byte[] buffer = new byte[1024];
int len;
while ((len = zis.read(buffer)) > 0) {
fos.write(buffer, 0, len);
}
fos.close();
}
zis.closeEntry();
zis.close();
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
```
在示例代码中,我们首先定义了要解压缩的zip文件路径和目标文件夹路径。然后我们调用`unzip`方法并传入这两个参数,该方法会将zip文件解压缩到目标文件夹中。
在`unzip`方法中,我们首先创建一个`FileInputStream`对象来读取zip文件,然后创建一个`ZipInputStream`对象来解压缩zip文件。我们使用`getNextEntry`方法遍历所有zip文件中的文件和文件夹,并将它们逐个解压缩到目标文件夹中。
在解压缩每个文件时,我们首先获取文件名并创建一个`File`对象来表示它。我们使用`mkdirs`方法创建所有不存在的父文件夹,然后创建一个`FileOutputStream`对象来将解压缩后的文件写入到磁盘中。
最后,我们在完成所有文件的解压缩后,关闭`ZipInputStream`和`FileInputStream`对象。