java代码压缩包解压
时间: 2023-09-07 17:17:10 浏览: 49
可以使用Java中的ZipInputStream和ZipEntry类来解压缩zip文件,以下是一个示例代码:
```java
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 ZipExtractor {
public static void main(String[] args) {
String zipFilePath = "path/to/zip/file.zip";
String destFolderPath = "path/to/destination/folder";
try {
unzip(zipFilePath, destFolderPath);
} catch (IOException e) {
e.printStackTrace();
}
}
public static void unzip(String zipFilePath, String destFolderPath) throws IOException {
File destDir = new File(destFolderPath);
if (!destDir.exists()) {
destDir.mkdir();
}
ZipInputStream zipIn = new ZipInputStream(new FileInputStream(zipFilePath));
ZipEntry entry = zipIn.getNextEntry();
while (entry != null) {
String filePath = destFolderPath + 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 {
byte[] buffer = new byte[1024];
File file = new File(filePath);
file.createNewFile();
FileOutputStream fos = new FileOutputStream(file);
int len;
while ((len = zipIn.read(buffer)) > 0) {
fos.write(buffer, 0, len);
}
fos.close();
}
}
```
在上面的代码中,zipFilePath是要解压缩的zip文件路径,destFolderPath是解压缩后要保存的文件夹路径。调用unzip方法即可完成解压缩。