JAVA解压缩文件——包含嵌套的压缩文件
时间: 2023-09-19 10:05:06 浏览: 70
Java中可以使用ZipInputStream和GZIPInputStream来解压缩压缩文件,其中ZipInputStream可以处理嵌套的压缩文件。
以下是一个用Java解压缩嵌套的压缩文件的示例代码:
```java
import java.io.*;
import java.util.zip.*;
public class UnzipExample {
public static void unzip(File zipFile, File destination) throws IOException {
byte[] buffer = new byte[1024];
try (ZipInputStream zis = new ZipInputStream(new FileInputStream(zipFile))) {
ZipEntry zipEntry = zis.getNextEntry();
while (zipEntry != null) {
File newFile = newFile(destination, zipEntry);
if (zipEntry.isDirectory()) {
if (!newFile.isDirectory() && !newFile.mkdirs()) {
throw new IOException("Failed to create directory " + newFile);
}
} else {
File parent = newFile.getParentFile();
if (!parent.isDirectory() && !parent.mkdirs()) {
throw new IOException("Failed to create directory " + parent);
}
try (FileOutputStream fos = new FileOutputStream(newFile)) {
int len;
while ((len = zis.read(buffer)) > 0) {
fos.write(buffer, 0, len);
}
}
}
zipEntry = zis.getNextEntry();
}
}
}
private static File newFile(File destinationDir, ZipEntry zipEntry) throws IOException {
File destFile = new File(destinationDir, zipEntry.getName());
String destDirPath = destinationDir.getCanonicalPath();
String destFilePath = destFile.getCanonicalPath();
if (!destFilePath.startsWith(destDirPath + File.separator)) {
throw new IOException("Entry is outside of the target directory: " + zipEntry.getName());
}
return destFile;
}
public static void main(String[] args) throws IOException {
File zipFile = new File("example.zip");
File destination = new File("unzipped");
unzip(zipFile, destination);
}
}
```
该示例代码使用了try-with-resources语句来确保关闭流,它还包含了一个newFile()方法,该方法用于检查解压缩文件的目录是否在指定的目标目录中。